@drift-labs/common 1.0.13 → 1.0.16
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.
- package/lib/clients/DlobWebsocketClient.d.ts +82 -0
- package/lib/clients/DlobWebsocketClient.js +226 -0
- package/lib/clients/DlobWebsocketClient.js.map +1 -0
- package/lib/clients/swiftClient.js +1 -0
- package/lib/clients/swiftClient.js.map +1 -1
- package/lib/common-ui-utils/commonUiUtils.d.ts +22 -3
- package/lib/common-ui-utils/commonUiUtils.js +15 -8
- package/lib/common-ui-utils/commonUiUtils.js.map +1 -1
- package/lib/common-ui-utils/market.d.ts +5 -0
- package/lib/common-ui-utils/market.js +19 -11
- package/lib/common-ui-utils/market.js.map +1 -1
- package/lib/common-ui-utils/order.d.ts +8 -1
- package/lib/common-ui-utils/order.js +3 -2
- package/lib/common-ui-utils/order.js.map +1 -1
- package/lib/common-ui-utils/user.d.ts +5 -0
- package/lib/common-ui-utils/user.js +58 -3
- package/lib/common-ui-utils/user.js.map +1 -1
- package/lib/constants/markets.d.ts +4 -0
- package/lib/constants/markets.js +5 -1
- package/lib/constants/markets.js.map +1 -1
- package/lib/constants/superstake.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +3 -2
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +52 -49
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
- package/lib/drift/Drift/data/PollingDlob.d.ts +1 -1
- package/lib/drift/Drift/data/PollingDlob.js.map +1 -1
- package/lib/drift/base/actions/trade/editOrder.d.ts +3 -0
- package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
- package/lib/drift/base/actions/trade/index.d.ts +1 -0
- package/lib/drift/base/actions/trade/index.js +1 -0
- package/lib/drift/base/actions/trade/index.js.map +1 -1
- package/lib/drift/base/actions/trade/margin.d.ts +24 -0
- package/lib/drift/base/actions/trade/margin.js +48 -0
- package/lib/drift/base/actions/trade/margin.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +3 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +2 -6
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +6 -3
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +6 -6
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +2 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +3 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +2 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/swap.d.ts +18 -11
- package/lib/drift/base/actions/trade/swap.js +40 -17
- package/lib/drift/base/actions/trade/swap.js.map +1 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/utils/MultiplexWebSocket.d.ts +4 -2
- package/lib/utils/MultiplexWebSocket.js +18 -9
- package/lib/utils/MultiplexWebSocket.js.map +1 -1
- package/lib/utils/ResultSlotIncrementer.d.ts +31 -0
- package/lib/utils/ResultSlotIncrementer.js +83 -0
- package/lib/utils/ResultSlotIncrementer.js.map +1 -0
- package/lib/utils/index.d.ts +3 -1
- package/lib/utils/index.js +7 -1
- package/lib/utils/index.js.map +1 -1
- package/lib/utils/math.js +1 -1
- package/lib/utils/math.js.map +1 -1
- package/lib/utils/orderbook/constants.d.ts +2 -0
- package/lib/utils/orderbook/constants.js +5 -0
- package/lib/utils/orderbook/constants.js.map +1 -0
- package/lib/utils/orderbook/index.d.ts +38 -59
- package/lib/utils/orderbook/index.js +285 -1
- package/lib/utils/orderbook/index.js.map +1 -1
- package/lib/utils/orderbook/types.d.ts +101 -0
- package/lib/utils/orderbook/types.js +9 -0
- package/lib/utils/orderbook/types.js.map +1 -0
- package/lib/utils/signedMsgs.d.ts +1 -0
- package/lib/utils/signedMsgs.js +10 -0
- package/lib/utils/signedMsgs.js.map +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;AAuDrE;;;;;;;;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,CAA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kB,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';\nimport { HighLeverageOptions } from '../../../../common-ui-utils/order';\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\t/** Optional high leverage options */\n\thighLeverageOptions?: HighLeverageOptions;\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"]}
|
|
@@ -18,4 +18,5 @@ __exportStar(require("./openPerpOrder"), exports);
|
|
|
18
18
|
__exportStar(require("./cancelOrder"), exports);
|
|
19
19
|
__exportStar(require("./editOrder"), exports);
|
|
20
20
|
__exportStar(require("./swap"), exports);
|
|
21
|
+
__exportStar(require("./margin"), exports);
|
|
21
22
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kDAAgC;AAChC,gDAA8B;AAC9B,8CAA4B;AAC5B,yCAAuB","sourcesContent":["export * from './openPerpOrder';\nexport * from './cancelOrder';\nexport * from './editOrder';\nexport * from './swap';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kDAAgC;AAChC,gDAA8B;AAC9B,8CAA4B;AAC5B,yCAAuB;AACvB,2CAAyB","sourcesContent":["export * from './openPerpOrder';\nexport * from './cancelOrder';\nexport * from './editOrder';\nexport * from './swap';\nexport * from './margin';\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { DriftClient, PerpMarketAccount, User } from '@drift-labs/sdk';
|
|
2
|
+
import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
|
+
import { WithTxnParams } from '../../types';
|
|
4
|
+
export interface CreateUpdateMarketMaxLeverageIxsParams {
|
|
5
|
+
driftClient: DriftClient;
|
|
6
|
+
user: User;
|
|
7
|
+
perpMarketAccount: PerpMarketAccount;
|
|
8
|
+
leverage: number;
|
|
9
|
+
mainSignerOverride?: PublicKey;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Creates transaction instructions to update a user's perp market max leverage
|
|
13
|
+
* @param params - Parameters for updating market max leverage
|
|
14
|
+
* @returns Promise that resolves to an array of transaction instructions
|
|
15
|
+
*/
|
|
16
|
+
export declare const createUpdateMarketMaxLeverageIxs: (params: CreateUpdateMarketMaxLeverageIxsParams) => Promise<TransactionInstruction[]>;
|
|
17
|
+
type CreateUpdateMarketMaxMarginTxnParams = WithTxnParams<CreateUpdateMarketMaxLeverageIxsParams>;
|
|
18
|
+
/**
|
|
19
|
+
* Creates a complete transaction to update a user's market max leverage
|
|
20
|
+
* @param params - Parameters for updating market max leverage, including optional transaction parameters
|
|
21
|
+
* @returns Promise that resolves to a Transaction or VersionedTransaction
|
|
22
|
+
*/
|
|
23
|
+
export declare const createUpdateMarketMaxLeverageTxn: ({ txParams, ...params }: CreateUpdateMarketMaxMarginTxnParams) => Promise<Transaction | VersionedTransaction>;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createUpdateMarketMaxLeverageTxn = exports.createUpdateMarketMaxLeverageIxs = void 0;
|
|
4
|
+
const sdk_1 = require("@drift-labs/sdk");
|
|
5
|
+
const trading_1 = require("../../../../common-ui-utils/trading");
|
|
6
|
+
const common_ui_utils_1 = require("../../../../common-ui-utils");
|
|
7
|
+
/**
|
|
8
|
+
* Creates transaction instructions to update a user's perp market max leverage
|
|
9
|
+
* @param params - Parameters for updating market max leverage
|
|
10
|
+
* @returns Promise that resolves to an array of transaction instructions
|
|
11
|
+
*/
|
|
12
|
+
const createUpdateMarketMaxLeverageIxs = async (params) => {
|
|
13
|
+
const { driftClient, perpMarketAccount, leverage, mainSignerOverride, user } = params;
|
|
14
|
+
const userAccount = user.getUserAccount();
|
|
15
|
+
const subAccountIdToUse = userAccount.subAccountId;
|
|
16
|
+
const ixs = [];
|
|
17
|
+
// Add enable High Leverage Mode ix for user if needed
|
|
18
|
+
const { maxLeverage: marketMaxNonHLLeverage } = common_ui_utils_1.MARKET_UTILS.getMaxLeverageForMarketAccount(sdk_1.MarketType.PERP, perpMarketAccount);
|
|
19
|
+
const isUserInHighLeverageMode = user.isHighLeverageMode('Initial');
|
|
20
|
+
const enableHLMForUser = !isUserInHighLeverageMode && marketMaxNonHLLeverage < leverage;
|
|
21
|
+
if (enableHLMForUser) {
|
|
22
|
+
ixs.push(await driftClient.getEnableHighLeverageModeIx(subAccountIdToUse, undefined, {
|
|
23
|
+
user,
|
|
24
|
+
signingAuthority: mainSignerOverride,
|
|
25
|
+
}));
|
|
26
|
+
}
|
|
27
|
+
// Update max leverage of perp market for user
|
|
28
|
+
const marginRatio = trading_1.TRADING_UTILS.convertLeverageToMarginRatio(leverage);
|
|
29
|
+
const perpMarketIndex = perpMarketAccount.marketIndex;
|
|
30
|
+
const updateMaxLeverageIx = await driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(perpMarketIndex, marginRatio, subAccountIdToUse, {
|
|
31
|
+
userAccountPublicKey: params.user.getUserAccountPublicKey(),
|
|
32
|
+
authority: userAccount.authority,
|
|
33
|
+
signingAuthority: mainSignerOverride,
|
|
34
|
+
});
|
|
35
|
+
ixs.push(updateMaxLeverageIx);
|
|
36
|
+
return ixs;
|
|
37
|
+
};
|
|
38
|
+
exports.createUpdateMarketMaxLeverageIxs = createUpdateMarketMaxLeverageIxs;
|
|
39
|
+
/**
|
|
40
|
+
* Creates a complete transaction to update a user's market max leverage
|
|
41
|
+
* @param params - Parameters for updating market max leverage, including optional transaction parameters
|
|
42
|
+
* @returns Promise that resolves to a Transaction or VersionedTransaction
|
|
43
|
+
*/
|
|
44
|
+
const createUpdateMarketMaxLeverageTxn = async ({ txParams, ...params }) => {
|
|
45
|
+
return params.driftClient.buildTransaction(await (0, exports.createUpdateMarketMaxLeverageIxs)(params), txParams);
|
|
46
|
+
};
|
|
47
|
+
exports.createUpdateMarketMaxLeverageTxn = createUpdateMarketMaxLeverageTxn;
|
|
48
|
+
//# sourceMappingURL=margin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"margin.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/margin.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AAQzB,iEAAoE;AACpE,iEAA2D;AAU3D;;;;GAIG;AACI,MAAM,gCAAgC,GAAG,KAAK,EACpD,MAA8C,EACV,EAAE;IACtC,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,QAAQ,EAAE,kBAAkB,EAAE,IAAI,EAAE,GAC3E,MAAM,CAAC;IAER,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;IAC1C,MAAM,iBAAiB,GAAG,WAAW,CAAC,YAAY,CAAC;IAEnD,MAAM,GAAG,GAA6B,EAAE,CAAC;IAEzC,sDAAsD;IACtD,MAAM,EAAE,WAAW,EAAE,sBAAsB,EAAE,GAC5C,8BAAY,CAAC,8BAA8B,CAC1C,gBAAU,CAAC,IAAI,EACf,iBAAiB,CACjB,CAAC;IACH,MAAM,wBAAwB,GAAG,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;IACpE,MAAM,gBAAgB,GACrB,CAAC,wBAAwB,IAAI,sBAAsB,GAAG,QAAQ,CAAC;IAEhE,IAAI,gBAAgB,EAAE,CAAC;QACtB,GAAG,CAAC,IAAI,CACP,MAAM,WAAW,CAAC,2BAA2B,CAC5C,iBAAiB,EACjB,SAAS,EACT;YACC,IAAI;YACJ,gBAAgB,EAAE,kBAAkB;SACpC,CACD,CACD,CAAC;IACH,CAAC;IAED,8CAA8C;IAC9C,MAAM,WAAW,GAAG,uBAAa,CAAC,4BAA4B,CAAC,QAAQ,CAAC,CAAC;IACzE,MAAM,eAAe,GAAG,iBAAiB,CAAC,WAAW,CAAC;IACtD,MAAM,mBAAmB,GACxB,MAAM,WAAW,CAAC,4CAA4C,CAC7D,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB;QACC,oBAAoB,EAAE,MAAM,CAAC,IAAI,CAAC,uBAAuB,EAAE;QAC3D,SAAS,EAAE,WAAW,CAAC,SAAS;QAChC,gBAAgB,EAAE,kBAAkB;KACpC,CACD,CAAC;IACH,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IAE9B,OAAO,GAAG,CAAC;AACZ,CAAC,CAAC;AAnDW,QAAA,gCAAgC,oCAmD3C;AAKF;;;;GAIG;AACI,MAAM,gCAAgC,GAAG,KAAK,EAAE,EACtD,QAAQ,EACR,GAAG,MAAM,EAC6B,EAErC,EAAE;IACH,OAAO,MAAM,CAAC,WAAW,CAAC,gBAAgB,CACzC,MAAM,IAAA,wCAAgC,EAAC,MAAM,CAAC,EAC9C,QAAQ,CACR,CAAC;AACH,CAAC,CAAC;AAVW,QAAA,gCAAgC,oCAU3C","sourcesContent":["import {\n\tDriftClient,\n\tMarketType,\n\tPerpMarketAccount,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { WithTxnParams } from '../../types';\nimport { TRADING_UTILS } from '../../../../common-ui-utils/trading';\nimport { MARKET_UTILS } from '../../../../common-ui-utils';\n\nexport interface CreateUpdateMarketMaxLeverageIxsParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tperpMarketAccount: PerpMarketAccount;\n\tleverage: number;\n\tmainSignerOverride?: PublicKey;\n}\n\n/**\n * Creates transaction instructions to update a user's perp market max leverage\n * @param params - Parameters for updating market max leverage\n * @returns Promise that resolves to an array of transaction instructions\n */\nexport const createUpdateMarketMaxLeverageIxs = async (\n\tparams: CreateUpdateMarketMaxLeverageIxsParams\n): Promise<TransactionInstruction[]> => {\n\tconst { driftClient, perpMarketAccount, leverage, mainSignerOverride, user } =\n\t\tparams;\n\n\tconst userAccount = user.getUserAccount();\n\tconst subAccountIdToUse = userAccount.subAccountId;\n\n\tconst ixs: TransactionInstruction[] = [];\n\n\t// Add enable High Leverage Mode ix for user if needed\n\tconst { maxLeverage: marketMaxNonHLLeverage } =\n\t\tMARKET_UTILS.getMaxLeverageForMarketAccount(\n\t\t\tMarketType.PERP,\n\t\t\tperpMarketAccount\n\t\t);\n\tconst isUserInHighLeverageMode = user.isHighLeverageMode('Initial');\n\tconst enableHLMForUser =\n\t\t!isUserInHighLeverageMode && marketMaxNonHLLeverage < leverage;\n\n\tif (enableHLMForUser) {\n\t\tixs.push(\n\t\t\tawait driftClient.getEnableHighLeverageModeIx(\n\t\t\t\tsubAccountIdToUse,\n\t\t\t\tundefined,\n\t\t\t\t{\n\t\t\t\t\tuser,\n\t\t\t\t\tsigningAuthority: mainSignerOverride,\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t}\n\n\t// Update max leverage of perp market for user\n\tconst marginRatio = TRADING_UTILS.convertLeverageToMarginRatio(leverage);\n\tconst perpMarketIndex = perpMarketAccount.marketIndex;\n\tconst updateMaxLeverageIx =\n\t\tawait driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(\n\t\t\tperpMarketIndex,\n\t\t\tmarginRatio,\n\t\t\tsubAccountIdToUse,\n\t\t\t{\n\t\t\t\tuserAccountPublicKey: params.user.getUserAccountPublicKey(),\n\t\t\t\tauthority: userAccount.authority,\n\t\t\t\tsigningAuthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\tixs.push(updateMaxLeverageIx);\n\n\treturn ixs;\n};\n\ntype CreateUpdateMarketMaxMarginTxnParams =\n\tWithTxnParams<CreateUpdateMarketMaxLeverageIxsParams>;\n\n/**\n * Creates a complete transaction to update a user's market max leverage\n * @param params - Parameters for updating market max leverage, including optional transaction parameters\n * @returns Promise that resolves to a Transaction or VersionedTransaction\n */\nexport const createUpdateMarketMaxLeverageTxn = async ({\n\ttxParams,\n\t...params\n}: CreateUpdateMarketMaxMarginTxnParams): Promise<\n\tTransaction | VersionedTransaction\n> => {\n\treturn params.driftClient.buildTransaction(\n\t\tawait createUpdateMarketMaxLeverageIxs(params),\n\t\ttxParams\n\t);\n};\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { PostOnlyParams, MarketType, BN, OptionalOrderParams, DriftClient, User, PositionDirection } from '@drift-labs/sdk';
|
|
2
|
+
import { HighLeverageOptions } from '../../../../../common-ui-utils';
|
|
2
3
|
import { LimitOrderParamsOrderConfig, LimitAuctionConfig } from './types';
|
|
3
|
-
export declare const getLimitAuctionOrderParams: ({ driftClient, user, marketIndex, marketType, direction, baseAssetAmount, userOrderId, reduceOnly, postOnly, orderConfig, }: {
|
|
4
|
+
export declare const getLimitAuctionOrderParams: ({ driftClient, user, marketIndex, marketType, direction, baseAssetAmount, userOrderId, reduceOnly, postOnly, orderConfig, highLeverageOptions, }: {
|
|
4
5
|
driftClient: DriftClient;
|
|
5
6
|
user: User;
|
|
6
7
|
marketIndex: number;
|
|
@@ -13,4 +14,5 @@ export declare const getLimitAuctionOrderParams: ({ driftClient, user, marketInd
|
|
|
13
14
|
orderConfig: LimitOrderParamsOrderConfig & {
|
|
14
15
|
limitAuction: LimitAuctionConfig;
|
|
15
16
|
};
|
|
17
|
+
highLeverageOptions?: HighLeverageOptions;
|
|
16
18
|
}) => Promise<OptionalOrderParams>;
|
|
@@ -10,7 +10,7 @@ const auction_1 = require("../../../constants/auction");
|
|
|
10
10
|
const utils_1 = require("../../../../../utils");
|
|
11
11
|
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
|
|
12
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, }) => {
|
|
13
|
+
const getLimitAuctionOrderParams = async ({ driftClient, user, marketIndex, marketType, direction, baseAssetAmount, userOrderId = 0, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, highLeverageOptions, }) => {
|
|
14
14
|
const orderParams = await (0, dlobServer_1.fetchAuctionOrderParams)({
|
|
15
15
|
driftClient,
|
|
16
16
|
user,
|
|
@@ -58,7 +58,7 @@ const getLimitAuctionOrderParams = async ({ driftClient, user, marketIndex, mark
|
|
|
58
58
|
});
|
|
59
59
|
const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
|
|
60
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);
|
|
61
|
+
const bitFlags = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction, highLeverageOptions);
|
|
62
62
|
return {
|
|
63
63
|
...limitAuctionOrderParams,
|
|
64
64
|
bitFlags,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auction.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/auction.ts"],"names":[],"mappings":";;;;;;AAAA,yCAayB;AACzB,
|
|
1
|
+
{"version":3,"file":"auction.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/auction.ts"],"names":[],"mappings":";;;;;;AAAA,yCAayB;AACzB,oEAIwC;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,EACX,mBAAmB,GAenB,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,IAAI,CAAC,CAAC;IAE7D,IAAA,wBAAS,EAAC,WAAW,CAAC,YAAY,CAAC,WAAW,EAAE,wBAAwB,CAAC,CAAC;IAC1E,IAAA,wBAAS,EAAC,WAAW,CAAC,iBAAiB,EAAE,+BAA+B,CAAC,CAAC;IAE1E,IAAI,gBAAgB,GAAyB,SAAS,CAAC;IACvD,IAAI,eAAe,GAAG,wCAA8B,CAAC;IAErD,IAAI,MAAM,EAAE,CAAC;QACZ,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;QACxE,IAAA,wBAAS,EAAC,MAAM,IAAI,iBAAiB,EAAE,+BAA+B,CAAC,CAAC;QAExE,gBAAgB,GAAG,WAAW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QAC1B,QAAQ;KACR,CAAC;AACH,CAAC,CAAC;AAtGW,QAAA,0BAA0B,8BAsGrC","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\tHighLeverageOptions,\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\thighLeverageOptions,\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\thighLeverageOptions?: HighLeverageOptions;\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\thighLeverageOptions\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { DriftClient, User, BN, PositionDirection, OptionalOrderParams, MarketType, UserAccount, PublicKey } from '@drift-labs/sdk';
|
|
2
2
|
import { MarketId, TradeOffsetPrice } from '../../../../../../types';
|
|
3
|
-
import {
|
|
3
|
+
import { DynamicSlippageConfig } from '../../../../../../utils/orderbook';
|
|
4
|
+
import { L2WithOracleAndMarketData } from '../../../../../../utils/orderbook/types';
|
|
4
5
|
export interface OptionalAuctionParamsRequestInputs {
|
|
5
6
|
maxLeverageSelected?: boolean;
|
|
6
7
|
maxLeverageOrderSize?: BN;
|
|
@@ -11,14 +12,9 @@ export interface OptionalAuctionParamsRequestInputs {
|
|
|
11
12
|
auctionStartPriceOffsetFrom?: TradeOffsetPrice;
|
|
12
13
|
auctionEndPriceOffsetFrom?: TradeOffsetPrice;
|
|
13
14
|
slippageTolerance?: number | 'dynamic';
|
|
14
|
-
auctionPriceCaps?: {
|
|
15
|
-
min: BN;
|
|
16
|
-
max: BN;
|
|
17
|
-
};
|
|
18
15
|
isOracleOrder?: boolean;
|
|
19
16
|
additionalEndPriceBuffer?: BN;
|
|
20
17
|
forceUpToSlippage?: boolean;
|
|
21
|
-
orderType?: 'market' | 'oracle';
|
|
22
18
|
}
|
|
23
19
|
interface RegularOrderParams {
|
|
24
20
|
driftClient: DriftClient;
|
|
@@ -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;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M,QAAQ,GAAG,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QAEzC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CACd,yBAAyB,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,UAAU,EAAE,CAClE,CAAC;QACH,CAAC;QAED,MAAM,cAAc,GAGd,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5B,MAAM,YAAY,GAGZ,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACpC,iBAAiB,EAAE,IAAI,eAAS,CAAC,KAAK,CAAC,iBAAiB,CAAC;YACzD,WAAW,EAAE,IAAA,gBAAU,EAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;SACnE,CAAC,CAAC,CAAC;QAEJ,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"]}
|
|
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,iEAK2C;AAK3C,uFAAoF;AACpF,qEAAiF;AACjF,uEAAoE;AACpE,oEAAuC;AAgDvC,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,CAAC,QAAQ,CAAC,MAAM;YACjC,YAAY,EAAE,CAAC,CAAC,QAAQ,CAAC,MAAM;YAC/B,eAAe,EAAE,CAAC,CAAC,QAAQ,CAAC,MAAM;YAClC,aAAa,EAAE,IAAI;YACnB,iBAAiB,EAAE,CAAC,0BAA0B;SAC9C,CAAC,CAAC;QACH,QAAQ,EAAE,YAAY;KACtB,CAAC;IAEF,MAAM,cAAc,GAIhB;QACH,UAAU,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC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AAS,GAAG,IAAA,yBAAiB,EAAC;YACnC,WAAW,EAAE,WAAW,CAAC,QAAQ,EAAE;YACnC,UAAU,EAAE,kBAAU,CAAC,KAAK,CAAC,UAAU,CAAC;YACxC,IAAI;YACJ,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE;YACvB,eAAe,EAAE,MAAM;SACvB,CAAC,CAAC;QAEH,MAAM,UAAU,GAAG,GAAG,iBAAiB,cAAc,SAAS,EAAE,CAAC;QACjE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QAEzC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CACd,yBAAyB,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,UAAU,EAAE,CAClE,CAAC;QACH,CAAC;QAED,MAAM,cAAc,GAGd,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5B,MAAM,YAAY,GAGZ,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACpC,iBAAiB,EAAE,IAAI,eAAS,CAAC,KAAK,CAAC,iBAAiB,CAAC;YACzD,WAAW,EAAE,IAAA,gBAAU,EAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;SACnE,CAAC,CAAC,CAAC;QAEJ,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\tcalculateDynamicSlippageFromL2,\n\tDynamicSlippageConfig,\n} from '../../../../../../utils/orderbook';\nimport {\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n} from '../../../../../../utils/orderbook/types';\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\tisOracleOrder?: boolean;\n\tadditionalEndPriceBuffer?: BN;\n\tforceUpToSlippage?: boolean;\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"]}
|
|
@@ -2,6 +2,7 @@ import { DriftClient, User, BN, PositionDirection, ReferrerInfo } from '@drift-l
|
|
|
2
2
|
import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
3
|
import { SwiftOrderOptions } from '../openSwiftOrder';
|
|
4
4
|
import { OptionalAuctionParamsRequestInputs } from '../dlobServer';
|
|
5
|
+
import { HighLeverageOptions } from '../../../../../../common-ui-utils/order';
|
|
5
6
|
import { WithTxnParams } from '../../../../types';
|
|
6
7
|
import { TxnOrSwiftResult } from '../types';
|
|
7
8
|
import { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';
|
|
@@ -60,6 +61,7 @@ export interface OpenPerpMarketOrderBaseParams {
|
|
|
60
61
|
*/
|
|
61
62
|
builderFeeTenthBps: number;
|
|
62
63
|
};
|
|
64
|
+
highLeverageOptions?: HighLeverageOptions;
|
|
63
65
|
}
|
|
64
66
|
export interface OpenPerpMarketOrderBaseParamsWithSwift extends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {
|
|
65
67
|
swiftOptions: SwiftOrderOptions;
|
|
@@ -76,12 +78,12 @@ export type OpenPerpMarketOrderParams<T extends boolean = boolean, S extends Omi
|
|
|
76
78
|
/**
|
|
77
79
|
* Creates and submits a Swift (signed message) order. Only available for perp orders.
|
|
78
80
|
*/
|
|
79
|
-
export declare function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId, positionMaxLeverage, builderParams, }: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void>;
|
|
81
|
+
export declare function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId, positionMaxLeverage, builderParams, highLeverageOptions, }: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void>;
|
|
80
82
|
/**
|
|
81
83
|
* Creates a placeAndTake transaction instruction.
|
|
82
84
|
* Fallbacks to a regular market order if no top makers are found.
|
|
83
85
|
*/
|
|
84
|
-
export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, mainSignerOverride, }: OpenPerpMarketOrderBaseParams & {
|
|
86
|
+
export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, mainSignerOverride, highLeverageOptions, }: OpenPerpMarketOrderBaseParams & {
|
|
85
87
|
direction: PositionDirection;
|
|
86
88
|
dlobServerHttpUrl: string;
|
|
87
89
|
marketIndex: number;
|
|
@@ -89,6 +91,7 @@ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, directio
|
|
|
89
91
|
user: User;
|
|
90
92
|
referrerInfo?: ReferrerInfo;
|
|
91
93
|
auctionDurationPercentage?: number;
|
|
94
|
+
highLeverageOptions?: HighLeverageOptions;
|
|
92
95
|
}) => Promise<TransactionInstruction>;
|
|
93
96
|
/**
|
|
94
97
|
* Creates transaction instructions for opening a perp market order.
|
|
@@ -107,7 +110,7 @@ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, directio
|
|
|
107
110
|
*
|
|
108
111
|
* @returns Promise resolving to an array of transaction instructions for regular orders
|
|
109
112
|
*/
|
|
110
|
-
export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, positionMaxLeverage, mainSignerOverride, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
|
|
113
|
+
export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, positionMaxLeverage, mainSignerOverride, highLeverageOptions, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
|
|
111
114
|
/**
|
|
112
115
|
* Creates a complete transaction for opening a perp market order.
|
|
113
116
|
*
|
|
@@ -12,7 +12,7 @@ const positionMaxLeverage_1 = require("../positionMaxLeverage");
|
|
|
12
12
|
/**
|
|
13
13
|
* Creates and submits a Swift (signed message) order. Only available for perp orders.
|
|
14
14
|
*/
|
|
15
|
-
async function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId = 0, positionMaxLeverage, builderParams, }) {
|
|
15
|
+
async function createSwiftMarketOrder({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, optionalAuctionParamsInputs, swiftOptions, userOrderId = 0, positionMaxLeverage, builderParams, highLeverageOptions, }) {
|
|
16
16
|
if (amount.isZero()) {
|
|
17
17
|
throw new Error('Amount must be greater than zero');
|
|
18
18
|
}
|
|
@@ -30,7 +30,7 @@ async function createSwiftMarketOrder({ driftClient, user, assetType, marketInde
|
|
|
30
30
|
});
|
|
31
31
|
const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
|
|
32
32
|
const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.BASE_PRECISION);
|
|
33
|
-
const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
|
|
33
|
+
const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction, highLeverageOptions);
|
|
34
34
|
const orderParams = {
|
|
35
35
|
...fetchedOrderParams,
|
|
36
36
|
userOrderId,
|
|
@@ -59,7 +59,7 @@ exports.createSwiftMarketOrder = createSwiftMarketOrder;
|
|
|
59
59
|
* Creates a placeAndTake transaction instruction.
|
|
60
60
|
* Fallbacks to a regular market order if no top makers are found.
|
|
61
61
|
*/
|
|
62
|
-
const createPlaceAndTakePerpMarketOrderIx = async ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, mainSignerOverride, }) => {
|
|
62
|
+
const createPlaceAndTakePerpMarketOrderIx = async ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, mainSignerOverride, highLeverageOptions, }) => {
|
|
63
63
|
const counterPartySide = utils_1.ENUM_UTILS.match(direction, sdk_1.PositionDirection.LONG)
|
|
64
64
|
? 'ask'
|
|
65
65
|
: 'bid';
|
|
@@ -85,7 +85,7 @@ const createPlaceAndTakePerpMarketOrderIx = async ({ assetType, direction, dlobS
|
|
|
85
85
|
]);
|
|
86
86
|
const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
|
|
87
87
|
const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.BASE_PRECISION);
|
|
88
|
-
const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
|
|
88
|
+
const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction, highLeverageOptions);
|
|
89
89
|
fetchedOrderParams.bitFlags = bitFlags;
|
|
90
90
|
fetchedOrderParams.userOrderId = userOrderId;
|
|
91
91
|
if (!topMakersResult || topMakersResult.length === 0) {
|
|
@@ -119,7 +119,7 @@ exports.createPlaceAndTakePerpMarketOrderIx = createPlaceAndTakePerpMarketOrderI
|
|
|
119
119
|
*
|
|
120
120
|
* @returns Promise resolving to an array of transaction instructions for regular orders
|
|
121
121
|
*/
|
|
122
|
-
const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs = {}, positionMaxLeverage, mainSignerOverride, }) => {
|
|
122
|
+
const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, marketIndex, direction, amount, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs = {}, positionMaxLeverage, mainSignerOverride, highLeverageOptions, }) => {
|
|
123
123
|
var _a, _b, _c, _d;
|
|
124
124
|
if (!amount || amount.isZero()) {
|
|
125
125
|
throw new Error('Amount must be greater than zero');
|
|
@@ -172,7 +172,7 @@ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, mark
|
|
|
172
172
|
});
|
|
173
173
|
const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
|
|
174
174
|
const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.BASE_PRECISION);
|
|
175
|
-
const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
|
|
175
|
+
const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction, highLeverageOptions);
|
|
176
176
|
const orderParams = {
|
|
177
177
|
...fetchedOrderParams,
|
|
178
178
|
userOrderId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../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AgB,CAAC;QAC3E,YAAY,EAAE,aAAa;QAC3B,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,WAAW,CAAC,UAAU;QAClC,mBAAmB,EAAE,WAAW;QAChC,iCAAiC,EAChC,WAAW,CAAC,2BAA2B,CAAC,IAAI,CAAC,WAAW,CAAC;QAC1D,QAAQ,EAAE,MAAM,CAAC,QAAQ;KACzB,CAAC,CAAC;IAEH,OAAO,sBAAsB,CAAC;AAC/B,CAAC,CAAC;AAlBW,QAAA,4BAA4B,gCAkBvC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,yBAAyB,GAAG,KAAK,EAC7C,MAAsE,EACvC,EAAE;IACjC,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEnD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CAAC;YACrD,GAAG,IAAI;YACP,YAAY;SACZ,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,sBAAsB,GAAG,MAAM,IAAA,oCAA4B,EAAC,IAAI,CAAC,CAAC;IAExE,OAAO,sBAA6C,CAAC;AACtD,CAAC,CAAC;AAtBW,QAAA,yBAAyB,6BAsBpC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tgetUserStatsAccountPublicKey,\n\tReferrerInfo,\n\tBASE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport { ORDER_COMMON_UTILS } from '../../../../../../common-ui-utils/order';\nimport { WithTxnParams } from '../../../../types';\nimport { TxnOrSwiftResult } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Optional per-market leverage to set for this position.\n\t * If provided and different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage?: number;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n\tpositionMaxLeverage,\n\tbuilderParams,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.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\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = swiftOptions.signedMessageOrderSlotBuffer || 7;\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n\tmainSignerOverride,\n}: OpenPerpMarketOrderBaseParams & {\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.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\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * adds an instruction to update the position's maxMarginRatio before placing the order.\n *\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n\tpositionMaxLeverage,\n\tmainSignerOverride,\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t\tmainSignerOverride,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = amount.mul(oraclePrice).div(BASE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * includes an instruction to update the position's maxMarginRatio.\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIxs = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIxs,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). Only supported for regular transactions (not Swift).\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,mDAAqD;AACrD,sDAG2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,mEAGiD;AAGjD,kEAAyE;AAEzE,gEAA0E;AAmF1E;;GAEG;AACI,KAAK,UAAU,sBAAsB,CAAC,EAC5C,WAAW,EACX,IAAI,EACJ,SAAS,EACT,WAAW,EACX,SAAS,EACT,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,2BAA2B,EAC3B,YAAY,EACZ,WAAW,GAAG,CAAC,EACf,mBAAmB,EACnB,aAAa,EACb,mBAAmB,GACqB;IACxC,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACrD,CAAC;IAED,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACxD,WAAW;QACX,IAAI;QACJ,SAAS;QACT,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT,MAAM;QACN,iBAAiB;QACjB,2BAA2B;KAC3B,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,WAAW,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,KAAK,CAAC;IAC9E,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,oBAAc,CAAC,CAAC;IAErE,MAAM,QAAQ,GAAG,0BAAkB,CAAC,0BAA0B,CAC7D,WAAW,EACX,WAAW,EACX,IAAI,EACJ,gBAAgB,EAChB,SAAS,EACT,mBAAmB,CACnB,CAAC;IAEF,MAAM,WAAW,GAAG;QACnB,GAAG,kBAAkB;QACrB,WAAW;QACX,QAAQ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E_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport {\n\tHighLeverageOptions,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils/order';\nimport { WithTxnParams } from '../../../../types';\nimport { TxnOrSwiftResult } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Optional per-market leverage to set for this position.\n\t * If provided and different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage?: number;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n\tpositionMaxLeverage,\n\tbuilderParams,\n\thighLeverageOptions,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.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\thighLeverageOptions\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = swiftOptions.signedMessageOrderSlotBuffer || 7;\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n\tmainSignerOverride,\n\thighLeverageOptions,\n}: OpenPerpMarketOrderBaseParams & {\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n\thighLeverageOptions?: HighLeverageOptions;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.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\thighLeverageOptions\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * adds an instruction to update the position's maxMarginRatio before placing the order.\n *\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n\tpositionMaxLeverage,\n\tmainSignerOverride,\n\thighLeverageOptions,\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t\tmainSignerOverride,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = amount.mul(oraclePrice).div(BASE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection,\n\t\t\thighLeverageOptions\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * includes an instruction to update the position's maxMarginRatio.\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIxs = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIxs,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). Only supported for regular transactions (not Swift).\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { DriftClient, User, BN, PostOnlyParams, PositionDirection } from '@drift-labs/sdk';
|
|
2
2
|
import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
3
|
import { SwiftOrderOptions } from '../openSwiftOrder';
|
|
4
|
+
import { HighLeverageOptions } from '../../../../../../common-ui-utils';
|
|
4
5
|
import { TxnOrSwiftResult, LimitOrderParamsOrderConfig, NonMarketOrderParamsConfig } from '../types';
|
|
5
6
|
import { WithTxnParams } from '../../../../types';
|
|
6
7
|
export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {
|
|
@@ -26,6 +27,7 @@ export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderPar
|
|
|
26
27
|
builderIdx: number;
|
|
27
28
|
builderFeeTenthBps: number;
|
|
28
29
|
};
|
|
30
|
+
highLeverageOptions?: HighLeverageOptions;
|
|
29
31
|
}
|
|
30
32
|
export interface OpenPerpNonMarketOrderParamsWithSwift extends OpenPerpNonMarketOrderBaseParams {
|
|
31
33
|
swiftOptions: SwiftOrderOptions;
|