@drift-labs/common 1.0.59 → 1.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/lib/_deprecated/common-math.d.ts +10 -0
  2. package/lib/_deprecated/common-math.js +9 -0
  3. package/lib/_deprecated/common-math.js.map +1 -0
  4. package/lib/_deprecated/common-ui-utils.d.ts +248 -0
  5. package/lib/_deprecated/common-ui-utils.js +59 -0
  6. package/lib/_deprecated/common-ui-utils.js.map +1 -0
  7. package/lib/_deprecated/equality-checks.d.ts +2 -0
  8. package/lib/_deprecated/equality-checks.js +7 -0
  9. package/lib/_deprecated/equality-checks.js.map +1 -0
  10. package/lib/{common-ui-utils/market.d.ts → _deprecated/market-utils.d.ts} +5 -7
  11. package/lib/_deprecated/market-utils.js +18 -0
  12. package/lib/_deprecated/market-utils.js.map +1 -0
  13. package/lib/_deprecated/order-utils.d.ts +12 -0
  14. package/lib/_deprecated/order-utils.js +18 -0
  15. package/lib/_deprecated/order-utils.js.map +1 -0
  16. package/lib/_deprecated/trading-utils.d.ts +52 -0
  17. package/lib/_deprecated/trading-utils.js +27 -0
  18. package/lib/_deprecated/trading-utils.js.map +1 -0
  19. package/lib/_deprecated/user-utils.d.ts +17 -0
  20. package/lib/_deprecated/user-utils.js +12 -0
  21. package/lib/_deprecated/user-utils.js.map +1 -0
  22. package/lib/_deprecated/utils.d.ts +40 -0
  23. package/lib/_deprecated/utils.js +47 -0
  24. package/lib/_deprecated/utils.js.map +1 -0
  25. package/lib/clients/tvFeed.js +2 -2
  26. package/lib/clients/tvFeed.js.map +1 -1
  27. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -8
  28. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  29. package/lib/drift/Drift/clients/AuthorityDrift/index.js +9 -9
  30. package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
  31. package/lib/drift/Drift/clients/CentralServerDrift/index.js +2 -2
  32. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  33. package/lib/drift/base/actions/trade/editOrder.d.ts +1 -1
  34. package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
  35. package/lib/drift/base/actions/trade/margin.js +4 -4
  36. package/lib/drift/base/actions/trade/margin.js.map +1 -1
  37. package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +1 -1
  38. package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -3
  39. package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
  40. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +2 -2
  41. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
  42. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +2 -2
  43. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
  44. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +1 -1
  45. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +4 -4
  46. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  47. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +1 -1
  48. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +2 -2
  49. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  50. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +4 -3
  51. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  52. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +2 -2
  53. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -1
  54. package/lib/drift/base/actions/user/create.js +2 -2
  55. package/lib/drift/base/actions/user/create.js.map +1 -1
  56. package/lib/drift/base/details/user/balances.js +2 -2
  57. package/lib/drift/base/details/user/balances.js.map +1 -1
  58. package/lib/drift/base/details/user/positions.js +2 -2
  59. package/lib/drift/base/details/user/positions.js.map +1 -1
  60. package/lib/index.d.ts +28 -28
  61. package/lib/index.js +44 -29
  62. package/lib/index.js.map +1 -1
  63. package/lib/utils/accounts/index.d.ts +6 -0
  64. package/lib/utils/accounts/index.js +23 -0
  65. package/lib/utils/accounts/index.js.map +1 -0
  66. package/lib/utils/accounts/init.d.ts +22 -0
  67. package/lib/utils/accounts/init.js +90 -0
  68. package/lib/utils/accounts/init.js.map +1 -0
  69. package/lib/utils/accounts/keys.d.ts +22 -0
  70. package/lib/utils/accounts/keys.js +36 -0
  71. package/lib/utils/accounts/keys.js.map +1 -0
  72. package/lib/utils/accounts/multiple.d.ts +14 -0
  73. package/lib/utils/accounts/multiple.js +45 -0
  74. package/lib/utils/accounts/multiple.js.map +1 -0
  75. package/lib/utils/accounts/signature.d.ts +6 -0
  76. package/lib/utils/accounts/signature.js +53 -0
  77. package/lib/utils/accounts/signature.js.map +1 -0
  78. package/lib/utils/accounts/subaccounts.d.ts +8 -0
  79. package/lib/utils/accounts/subaccounts.js +31 -0
  80. package/lib/utils/accounts/subaccounts.js.map +1 -0
  81. package/lib/utils/{WalletConnectionState.d.ts → accounts/wallet.d.ts} +7 -1
  82. package/lib/utils/{WalletConnectionState.js → accounts/wallet.js} +32 -2
  83. package/lib/utils/accounts/wallet.js.map +1 -0
  84. package/lib/utils/core/arrays.d.ts +2 -0
  85. package/lib/utils/core/arrays.js +25 -0
  86. package/lib/utils/core/arrays.js.map +1 -0
  87. package/lib/utils/core/async.d.ts +5 -0
  88. package/lib/utils/core/async.js +17 -0
  89. package/lib/utils/core/async.js.map +1 -0
  90. package/lib/utils/core/cache.d.ts +1 -0
  91. package/lib/utils/core/cache.js +40 -0
  92. package/lib/utils/core/cache.js.map +1 -0
  93. package/lib/utils/core/data-structures.d.ts +30 -0
  94. package/lib/utils/core/data-structures.js +84 -0
  95. package/lib/utils/core/data-structures.js.map +1 -0
  96. package/lib/utils/{equalityChecks.d.ts → core/equality.d.ts} +1 -1
  97. package/lib/utils/{equalityChecks.js → core/equality.js} +3 -3
  98. package/lib/utils/core/equality.js.map +1 -0
  99. package/lib/utils/core/fetch.js.map +1 -0
  100. package/lib/utils/core/index.d.ts +7 -0
  101. package/lib/utils/core/index.js +24 -0
  102. package/lib/utils/core/index.js.map +1 -0
  103. package/lib/utils/core/serialization.d.ts +30 -0
  104. package/lib/utils/core/serialization.js +92 -0
  105. package/lib/utils/core/serialization.js.map +1 -0
  106. package/lib/utils/{enum.js → enum/index.js} +1 -1
  107. package/lib/utils/enum/index.js.map +1 -0
  108. package/lib/utils/index.d.ts +11 -176
  109. package/lib/utils/index.js +25 -594
  110. package/lib/utils/index.js.map +1 -1
  111. package/lib/utils/markets/balances.d.ts +6 -0
  112. package/lib/utils/markets/balances.js +29 -0
  113. package/lib/utils/markets/balances.js.map +1 -0
  114. package/lib/utils/markets/config.d.ts +5 -0
  115. package/lib/utils/markets/config.js +24 -0
  116. package/lib/utils/markets/config.js.map +1 -0
  117. package/lib/utils/markets/index.d.ts +6 -0
  118. package/lib/utils/markets/index.js +23 -0
  119. package/lib/utils/markets/index.js.map +1 -0
  120. package/lib/utils/markets/interest.d.ts +25 -0
  121. package/lib/utils/markets/interest.js +65 -0
  122. package/lib/utils/markets/interest.js.map +1 -0
  123. package/lib/utils/markets/leverage.d.ts +12 -0
  124. package/lib/utils/markets/leverage.js +60 -0
  125. package/lib/utils/markets/leverage.js.map +1 -0
  126. package/lib/utils/markets/operations.d.ts +21 -0
  127. package/lib/utils/markets/operations.js +59 -0
  128. package/lib/utils/markets/operations.js.map +1 -0
  129. package/lib/utils/math/bignum.d.ts +3 -0
  130. package/lib/utils/math/bignum.js +16 -0
  131. package/lib/utils/math/bignum.js.map +1 -0
  132. package/lib/utils/math/bn.d.ts +7 -0
  133. package/lib/utils/math/bn.js +58 -0
  134. package/lib/utils/math/bn.js.map +1 -0
  135. package/lib/utils/math/index.d.ts +7 -0
  136. package/lib/utils/math/index.js +24 -0
  137. package/lib/utils/math/index.js.map +1 -0
  138. package/lib/utils/math/numbers.d.ts +13 -0
  139. package/lib/utils/math/numbers.js +56 -0
  140. package/lib/utils/math/numbers.js.map +1 -0
  141. package/lib/utils/math/precision.d.ts +19 -0
  142. package/lib/utils/math/precision.js +73 -0
  143. package/lib/utils/math/precision.js.map +1 -0
  144. package/lib/utils/math/price.d.ts +12 -0
  145. package/lib/utils/math/price.js +45 -0
  146. package/lib/utils/math/price.js.map +1 -0
  147. package/lib/utils/math/sort.d.ts +13 -0
  148. package/lib/utils/math/sort.js +33 -0
  149. package/lib/utils/math/sort.js.map +1 -0
  150. package/lib/utils/math/spread.d.ts +8 -0
  151. package/lib/utils/math/spread.js +87 -0
  152. package/lib/utils/math/spread.js.map +1 -0
  153. package/lib/utils/orderbook/index.js +4 -4
  154. package/lib/utils/orderbook/index.js.map +1 -1
  155. package/lib/utils/orders/filters.d.ts +7 -0
  156. package/lib/utils/orders/filters.js +31 -0
  157. package/lib/utils/orders/filters.js.map +1 -0
  158. package/lib/utils/orders/flags.d.ts +12 -0
  159. package/lib/utils/orders/flags.js +44 -0
  160. package/lib/utils/orders/flags.js.map +1 -0
  161. package/lib/utils/orders/index.d.ts +6 -0
  162. package/lib/utils/orders/index.js +23 -0
  163. package/lib/utils/orders/index.js.map +1 -0
  164. package/lib/utils/orders/labels.d.ts +4 -0
  165. package/lib/utils/orders/labels.js +122 -0
  166. package/lib/utils/orders/labels.js.map +1 -0
  167. package/lib/utils/orders/misc.d.ts +11 -0
  168. package/lib/utils/orders/misc.js +27 -0
  169. package/lib/utils/orders/misc.js.map +1 -0
  170. package/lib/utils/orders/oracle.d.ts +5 -0
  171. package/lib/utils/orders/oracle.js +23 -0
  172. package/lib/utils/orders/oracle.js.map +1 -0
  173. package/lib/utils/orders/sort.d.ts +38 -0
  174. package/lib/utils/orders/sort.js +83 -0
  175. package/lib/utils/orders/sort.js.map +1 -0
  176. package/lib/utils/positions/index.d.ts +2 -0
  177. package/lib/{common-ui-utils → utils/positions}/index.js +1 -5
  178. package/lib/utils/positions/index.js.map +1 -0
  179. package/lib/utils/positions/open.d.ts +4 -0
  180. package/lib/{common-ui-utils/user.js → utils/positions/open.js} +10 -81
  181. package/lib/utils/positions/open.js.map +1 -0
  182. package/lib/utils/positions/user.d.ts +37 -0
  183. package/lib/utils/positions/user.js +74 -0
  184. package/lib/utils/positions/user.js.map +1 -0
  185. package/lib/utils/settings/settings.js.map +1 -0
  186. package/lib/utils/strings/convert.d.ts +11 -0
  187. package/lib/utils/{strings.js → strings/convert.js} +2 -51
  188. package/lib/utils/strings/convert.js.map +1 -0
  189. package/lib/utils/strings/format.d.ts +14 -0
  190. package/lib/utils/strings/format.js +61 -0
  191. package/lib/utils/strings/format.js.map +1 -0
  192. package/lib/utils/strings/index.d.ts +4 -0
  193. package/lib/utils/strings/index.js +21 -0
  194. package/lib/utils/strings/index.js.map +1 -0
  195. package/lib/utils/strings/parse.d.ts +4 -0
  196. package/lib/utils/strings/parse.js +25 -0
  197. package/lib/utils/strings/parse.js.map +1 -0
  198. package/lib/utils/strings/status.d.ts +15 -0
  199. package/lib/utils/strings/status.js +21 -0
  200. package/lib/utils/strings/status.js.map +1 -0
  201. package/lib/utils/token/account.d.ts +16 -0
  202. package/lib/utils/token/account.js +36 -0
  203. package/lib/utils/token/account.js.map +1 -0
  204. package/lib/utils/{token.d.ts → token/address.d.ts} +2 -7
  205. package/lib/utils/token/address.js +30 -0
  206. package/lib/utils/token/address.js.map +1 -0
  207. package/lib/utils/token/index.d.ts +3 -0
  208. package/lib/utils/token/index.js +20 -0
  209. package/lib/utils/token/index.js.map +1 -0
  210. package/lib/utils/token/instructions.d.ts +3 -0
  211. package/lib/utils/token/instructions.js +17 -0
  212. package/lib/utils/token/instructions.js.map +1 -0
  213. package/lib/utils/trading/auction.d.ts +82 -0
  214. package/lib/utils/trading/auction.js +208 -0
  215. package/lib/utils/trading/auction.js.map +1 -0
  216. package/lib/utils/trading/index.d.ts +7 -0
  217. package/lib/utils/trading/index.js +24 -0
  218. package/lib/utils/trading/index.js.map +1 -0
  219. package/lib/utils/trading/leverage.d.ts +18 -0
  220. package/lib/utils/trading/leverage.js +79 -0
  221. package/lib/utils/trading/leverage.js.map +1 -0
  222. package/lib/utils/trading/liquidation.d.ts +22 -0
  223. package/lib/utils/trading/liquidation.js +67 -0
  224. package/lib/utils/trading/liquidation.js.map +1 -0
  225. package/lib/utils/trading/lp.d.ts +4 -0
  226. package/lib/utils/trading/lp.js +20 -0
  227. package/lib/utils/trading/lp.js.map +1 -0
  228. package/lib/utils/trading/pnl.d.ts +34 -0
  229. package/lib/utils/trading/pnl.js +88 -0
  230. package/lib/utils/trading/pnl.js.map +1 -0
  231. package/lib/utils/trading/price.d.ts +12 -0
  232. package/lib/utils/trading/price.js +36 -0
  233. package/lib/utils/trading/price.js.map +1 -0
  234. package/lib/utils/trading/size.d.ts +27 -0
  235. package/lib/utils/trading/size.js +83 -0
  236. package/lib/utils/trading/size.js.map +1 -0
  237. package/lib/utils/{validation.d.ts → validation/address.d.ts} +1 -2
  238. package/lib/utils/{validation.js → validation/address.js} +4 -6
  239. package/lib/utils/validation/address.js.map +1 -0
  240. package/lib/utils/validation/index.d.ts +3 -0
  241. package/lib/utils/validation/index.js +20 -0
  242. package/lib/utils/validation/index.js.map +1 -0
  243. package/lib/utils/validation/input.d.ts +3 -0
  244. package/lib/utils/validation/input.js +33 -0
  245. package/lib/utils/validation/input.js.map +1 -0
  246. package/lib/utils/validation/notional.d.ts +2 -0
  247. package/lib/utils/validation/notional.js +8 -0
  248. package/lib/utils/validation/notional.js.map +1 -0
  249. package/package.json +90 -3
  250. package/lib/common-ui-utils/commonUiUtils.d.ts +0 -251
  251. package/lib/common-ui-utils/commonUiUtils.js +0 -647
  252. package/lib/common-ui-utils/commonUiUtils.js.map +0 -1
  253. package/lib/common-ui-utils/index.d.ts +0 -6
  254. package/lib/common-ui-utils/index.js.map +0 -1
  255. package/lib/common-ui-utils/market.js +0 -134
  256. package/lib/common-ui-utils/market.js.map +0 -1
  257. package/lib/common-ui-utils/order.d.ts +0 -25
  258. package/lib/common-ui-utils/order.js +0 -191
  259. package/lib/common-ui-utils/order.js.map +0 -1
  260. package/lib/common-ui-utils/settings/settings.js.map +0 -1
  261. package/lib/common-ui-utils/trading.d.ts +0 -79
  262. package/lib/common-ui-utils/trading.js +0 -313
  263. package/lib/common-ui-utils/trading.js.map +0 -1
  264. package/lib/common-ui-utils/user.d.ts +0 -18
  265. package/lib/common-ui-utils/user.js.map +0 -1
  266. package/lib/utils/WalletConnectionState.js.map +0 -1
  267. package/lib/utils/enum.js.map +0 -1
  268. package/lib/utils/equalityChecks.js.map +0 -1
  269. package/lib/utils/fetch.js.map +0 -1
  270. package/lib/utils/math.d.ts +0 -31
  271. package/lib/utils/math.js +0 -181
  272. package/lib/utils/math.js.map +0 -1
  273. package/lib/utils/strings.d.ts +0 -34
  274. package/lib/utils/strings.js.map +0 -1
  275. package/lib/utils/token.js +0 -45
  276. package/lib/utils/token.js.map +0 -1
  277. package/lib/utils/validation.js.map +0 -1
  278. /package/lib/utils/{fetch.d.ts → core/fetch.d.ts} +0 -0
  279. /package/lib/utils/{fetch.js → core/fetch.js} +0 -0
  280. /package/lib/utils/{enum.d.ts → enum/index.d.ts} +0 -0
  281. /package/lib/{common-ui-utils → utils}/settings/settings.d.ts +0 -0
  282. /package/lib/{common-ui-utils → utils}/settings/settings.js +0 -0
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createUpdateMarketMaxLeverageTxn = exports.createUpdateMarketMaxLeverageIxs = void 0;
4
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");
5
+ const trading_utils_1 = require("../../../../_deprecated/trading-utils");
6
+ const market_utils_1 = require("../../../../_deprecated/market-utils");
7
7
  /**
8
8
  * Creates transaction instructions to update a user's perp market max leverage
9
9
  * @param params - Parameters for updating market max leverage
@@ -15,7 +15,7 @@ const createUpdateMarketMaxLeverageIxs = async (params) => {
15
15
  const subAccountIdToUse = userAccount.subAccountId;
16
16
  const ixs = [];
17
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);
18
+ const { maxLeverage: marketMaxNonHLLeverage } = market_utils_1.MARKET_UTILS.getMaxLeverageForMarketAccount(sdk_1.MarketType.PERP, perpMarketAccount);
19
19
  const isUserInHighLeverageMode = user.isHighLeverageMode('Initial');
20
20
  const enableHLMForUser = !isUserInHighLeverageMode && marketMaxNonHLLeverage < leverage;
21
21
  if (enableHLMForUser) {
@@ -25,7 +25,7 @@ const createUpdateMarketMaxLeverageIxs = async (params) => {
25
25
  }));
26
26
  }
27
27
  // Update max leverage of perp market for user
28
- const marginRatio = trading_1.TRADING_UTILS.convertLeverageToMarginRatio(leverage);
28
+ const marginRatio = trading_utils_1.TRADING_UTILS.convertLeverageToMarginRatio(leverage);
29
29
  const perpMarketIndex = perpMarketAccount.marketIndex;
30
30
  const updateMaxLeverageIx = await driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(perpMarketIndex, marginRatio, subAccountIdToUse, {
31
31
  userAccountPublicKey: params.user.getUserAccountPublicKey(),
@@ -1 +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,MAA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H,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
+ {"version":3,"file":"margin.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/margin.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AAQzB,yEAAsE;AACtE,uEAAoE;AAUpE;;;;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,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,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 '../../../../_deprecated/trading-utils';\nimport { MARKET_UTILS } from '../../../../_deprecated/market-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,5 +1,5 @@
1
1
  import { PostOnlyParams, MarketType, BN, OptionalOrderParams, DriftClient, User, PositionDirection } from '@drift-labs/sdk';
2
- import { HighLeverageOptions } from '../../../../../common-ui-utils';
2
+ import { HighLeverageOptions } from '../../../../../utils/orders';
3
3
  import { LimitOrderParamsOrderConfig, LimitAuctionConfig } from './types';
4
4
  import { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';
5
5
  export declare const getLimitAuctionOrderParams: ({ driftClient, user, marketIndex, marketType, direction, baseAssetAmount, positionMaxLeverage, userOrderId, reduceOnly, postOnly, orderConfig, highLeverageOptions, onAuctionParamsFetched, }: {
@@ -5,7 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getLimitAuctionOrderParams = void 0;
7
7
  const sdk_1 = require("@drift-labs/sdk");
8
- const common_ui_utils_1 = require("../../../../../common-ui-utils");
8
+ const order_utils_1 = require("../../../../../_deprecated/order-utils");
9
+ const common_ui_utils_1 = require("../../../../../_deprecated/common-ui-utils");
9
10
  const auction_1 = require("../../../constants/auction");
10
11
  const utils_1 = require("../../../../../utils");
11
12
  const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
@@ -37,7 +38,7 @@ const getLimitAuctionOrderParams = async ({ driftClient, user, marketIndex, mark
37
38
  price: orderConfig.limitAuction.oraclePrice,
38
39
  })
39
40
  : undefined;
40
- auctionDuration = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpAuctionDuration(orderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(), orderConfig.limitAuction.oraclePrice, perpMarketAccount.contractTier);
41
+ auctionDuration = order_utils_1.ORDER_COMMON_UTILS.getPerpAuctionDuration(orderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(), orderConfig.limitAuction.oraclePrice, perpMarketAccount.contractTier);
41
42
  }
42
43
  const limitAuctionParams = common_ui_utils_1.COMMON_UI_UTILS.getLimitAuctionParams({
43
44
  direction,
@@ -58,7 +59,7 @@ const getLimitAuctionOrderParams = async ({ driftClient, user, marketIndex, mark
58
59
  userOrderId,
59
60
  ...limitAuctionParams,
60
61
  });
61
- const bitFlags = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
62
+ const bitFlags = order_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
62
63
  return {
63
64
  ...limitAuctionOrderParams,
64
65
  bitFlags,
@@ -1 +1 @@
1
- {"version":3,"file":"auction.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/auction.ts"],"names":[],"mappings":";;;;;;AAAA,yCAYyB;AACzB,oEAIwC;AACxC,wDAA4E;AAC5E,gDAAkD;AAClD,oEAAuC;AACvC,6CAAuD;AAIhD,MAAM,0BAA0B,GAAG,KAAK,EAAE,EAChD,WAAW,EACX,IAAI,EACJ,WAAW,EACX,UAAU,EACV,SAAS,EACT,eAAe,EACf,mBAAmB,EACnB,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,EACX,mBAAmB,EACnB,sBAAsB,GAiBtB,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,UAAU;QACV,iBAAiB,EAAE,WAAW,CAAC,YAAY,CAAC,iBAAiB;QAC7D,2BAA2B,EAC1B,WAAW,CAAC,YAAY,CAAC,0BAA0B;QACpD,sBAAsB,EAAE,sBAAsB;KAC9C,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,CA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n\tPostOnlyParams,\n\tMarketType,\n\tBN,\n\tOptionalOrderParams,\n\tBigNum,\n\tPRICE_PRECISION_EXP,\n\tgetLimitOrderParams,\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';\nimport { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';\n\nexport const getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tbaseAssetAmount,\n\tpositionMaxLeverage,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n\thighLeverageOptions,\n\tonAuctionParamsFetched,\n}: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\tpositionMaxLeverage: number;\n\tuserOrderId?: number;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\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\treduceOnly,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\tonAuctionParamsFetched: onAuctionParamsFetched,\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 bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n"]}
1
+ {"version":3,"file":"auction.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/auction.ts"],"names":[],"mappings":";;;;;;AAAA,yCAYyB;AACzB,wEAA4E;AAC5E,gFAA6E;AAE7E,wDAA4E;AAC5E,gDAAkD;AAClD,oEAAuC;AACvC,6CAAuD;AAIhD,MAAM,0BAA0B,GAAG,KAAK,EAAE,EAChD,WAAW,EACX,IAAI,EACJ,WAAW,EACX,UAAU,EACV,SAAS,EACT,eAAe,EACf,mBAAmB,EACnB,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,EACX,mBAAmB,EACnB,sBAAsB,GAiBtB,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,UAAU;QACV,iBAAiB,EAAE,WAAW,CAAC,YAAY,CAAC,iBAAiB;QAC7D,2BAA2B,EAC1B,WAAW,CAAC,YAAY,CAAC,0BAA0B;QACpD,sBAAsB,EAAE,sBAAsB;KAC9C,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,IAA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,EACJ,mBAAmB,EACnB,mBAAmB,CACnB,CAAC;IAEF,OAAO;QACN,GAAG,uBAAuB;QAC1B,QAAQ;KACR,CAAC;AACH,CAAC,CAAC;AAxGW,QAAA,0BAA0B,8BAwGrC","sourcesContent":["import {\n\tPostOnlyParams,\n\tMarketType,\n\tBN,\n\tOptionalOrderParams,\n\tBigNum,\n\tPRICE_PRECISION_EXP,\n\tgetLimitOrderParams,\n\toraclePriceBands as getOraclePriceBands,\n\tDriftClient,\n\tUser,\n\tPositionDirection,\n} from '@drift-labs/sdk';\nimport { ORDER_COMMON_UTILS } from '../../../../../_deprecated/order-utils';\nimport { COMMON_UI_UTILS } from '../../../../../_deprecated/common-ui-utils';\nimport { HighLeverageOptions } from '../../../../../utils/orders';\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';\nimport { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';\n\nexport const getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tbaseAssetAmount,\n\tpositionMaxLeverage,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n\thighLeverageOptions,\n\tonAuctionParamsFetched,\n}: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\tpositionMaxLeverage: number;\n\tuserOrderId?: number;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\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\treduceOnly,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\tonAuctionParamsFetched: onAuctionParamsFetched,\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 bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n"]}
@@ -7,12 +7,12 @@ exports.fetchTopMakers = exports.fetchAuctionOrderParamsFromL2 = exports.fetchAu
7
7
  const sdk_1 = require("@drift-labs/sdk");
8
8
  const utils_1 = require("../../../../../../utils");
9
9
  const auctionParamsResponseMapper_1 = require("../../../../../utils/auctionParamsResponseMapper");
10
- const fetch_1 = require("../../../../../../utils/fetch");
10
+ const fetch_1 = require("../../../../../../utils/core/fetch");
11
11
  const types_1 = require("../../../../../../types");
12
12
  const orderbook_1 = require("../../../../../../utils/orderbook");
13
13
  const pollingSequenceGuard_1 = require("../../../../../../utils/pollingSequenceGuard");
14
14
  const priceImpact_1 = require("../../../../../../utils/priceImpact");
15
- const common_ui_utils_1 = require("../../../../../../common-ui-utils");
15
+ const common_ui_utils_1 = require("../../../../../../_deprecated/common-ui-utils");
16
16
  const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
17
17
  const BACKGROUND_L2_POLLING_KEY = Symbol('BACKGROUND_L2_POLLING_KEY');
18
18
  /**
@@ -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,kGAK0D;AAC1D,yDAAkE;AAClE,mDAAqE;AACrE,iEAK2C;AAK3C,uFAAoF;AACpF,qEAAiF;AACjF,uE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,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\tAuctionParamsFetchedCallback,\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\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\tdlobServerHttpUrl: string;\n\treduceOnly?: boolean;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\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\treduceOnly,\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\treduceOnly: reduceOnly ? 'true' : 'false',\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 || 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\treduceOnly,\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: 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,kGAK0D;AAC1D,8DAAuE;AACvE,mDAAqE;AACrE,iEAK2C;AAK3C,uFAAoF;AACpF,qEAAiF;AACjF,mFAAgF;AAChF,oEAAuC;AAiDvC,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,M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ams,\n\tBASE_PRECISION,\n\tTEN,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tmapAuctionParamsResponse,\n\tServerAuctionParamsResponse,\n\tMappedAuctionParams,\n\tAuctionParamsFetchedCallback,\n} from '../../../../../utils/auctionParamsResponseMapper';\nimport { encodeQueryParams } from '../../../../../../utils/core/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 '../../../../../../_deprecated/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\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\tdlobServerHttpUrl: string;\n\treduceOnly?: boolean;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\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\treduceOnly,\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\treduceOnly: reduceOnly ? 'true' : 'false',\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 || 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\treduceOnly,\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: 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,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getIsolatedPositionDepositIxIfNeeded = exports.resolveIsolatedPositionDepositsWithOverride = exports.resolveIsolatedPositionDeposits = exports.calculateIsolatedPositionDeposits = exports.UnderwaterIsolatedPositionsError = exports.computeIsolatedPositionDepositForTrade = exports.getTotalIsolatedMarginShortfall = exports.getOtherIsolatedMarginShortfalls = exports.getIsolatedMarginShortfall = exports.getIsolatedMarginShortfalls = exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
- const trading_1 = require("../../../../../common-ui-utils/trading");
5
+ const trading_utils_1 = require("../../../../../_deprecated/trading-utils");
6
6
  const positionMarginMode_1 = require("../../../details/user/positionMarginMode");
7
7
  exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;
8
8
  /**
@@ -126,7 +126,7 @@ function calculateIsolatedPositionDeposits(params) {
126
126
  // Extract current market's shortfall from the pre-computed map
127
127
  const currentMarketShortfall = (_a = allShortfalls.get(params.marketIndex)) !== null && _a !== void 0 ? _a : sdk_1.ZERO;
128
128
  let mainIsolatedPositionDeposit;
129
- const marginRatio = trading_1.TRADING_UTILS.convertLeverageToMarginRatio(params.positionMaxLeverage);
129
+ const marginRatio = trading_utils_1.TRADING_UTILS.convertLeverageToMarginRatio(params.positionMaxLeverage);
130
130
  if (marginRatio) {
131
131
  mainIsolatedPositionDeposit = computeIsolatedPositionDepositForTrade({
132
132
  driftClient: params.driftClient,
@@ -1 +1 @@
1
- {"version":3,"file":"isolatedPositionDeposit.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAEzB,oEAAuE;AAKvE,iFAAiF;AAEpE,QAAA,oCAAoC,GAAG,EAAE,CAAC;AAOvD;;;;GAIG;AACH,SAAgB,2BAA2B,CAAC,IAAU;IACrD,MAAM,UAAU,GAAG,IAAI,GAAG,EAAc,CAAC;IAEzC,MAAM,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAExD,KAAK,MAAM,CACV,WAAW,EACX,YAAY,EACZ,IAAI,UAAU,CAAC,0BAA0B,EAAE,CAAC;QAC5C,MAAM,SAAS,GAAG,YAAY,CAAC,cAAc,EAAE,CAAC;QAChD,IAAI,SAAS,CAAC,EAAE,CAAC,UAAI,CAAC,EAAE,CAAC;YACxB,UAAU,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;QACxC,CAAC;IACF,CAAC;IAED,OAAO,UAAU,CAAC;AACnB,CAAC;AAhBD,kEAgBC;AAED;;;GAGG;AACH,SAAgB,0BAA0B,CACzC,IAAU,EACV,WAAmB;IAEnB,MAAM,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACxD,MAAM,YAAY,GAAG,UAAU,CAAC,0BAA0B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAE5E,IAAI,CAAC,YAAY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UAAU;QAAE,OAAO,SAAS,CAAC;IAElC,OAAO,iCAAiC,CAAC,MAAM,CAAC,CAAC;AAClD,CAAC;AAlBD,0EAkBC;AAED;;;;GAIG;AACH,SAAgB,2CAA2C,CAC1D,QAAsD,EACtD,aAAoE;IAEpE,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5B,OAAO;YACN,WAAW,EAAE,QAAQ,CAAC,WAAW;YACjC,kCAAkC,EAAE,QAAQ,CAAC,kBAAkB;SAC/D,CAAC;IACH,CAAC;IACD,OAAO,+BAA+B,CAAC,aAAa,CAAC,CAAC;AACvD,CAAC;AAXD,kGAWC;AAEM,KAAK,UAAU,oCAAoC,CACzD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,uBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,uBAAuB,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,WAAW,CAAC,wCAAwC,CAC1D,uBAAuB,EACvB,WAAW,EACX,IAAI,CAAC,cAAc,EAAE,CAAC,YAAY,EAClC,SAAS,EAAE,iBAAiB;IAC5B,gBAAgB,CAChB,CAAC;AACH,CAAC;AArBD,oFAqBC","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tUser,\n\tcalculateMarginUSDCRequiredForTrade,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tMarketType,\n\tOrderType,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport {\n\tAdditionalIsolatedPositionDeposit,\n\tIsolatedPositionDepositsOverride,\n} from './types';\nimport { getPositionMarginMode } from '../../../details/user/positionMarginMode';\n\nexport const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;\n\nexport interface IsolatedMarginShortfall {\n\tmarketIndex: number;\n\tshortfall: BN;\n}\n\n/**\n * Computes the initial margin shortfall for all isolated perp positions.\n * Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).\n * Only includes positions that are under initial margin (shortfall > 0).\n */\nexport function getIsolatedMarginShortfalls(user: User): Map<number, BN> {\n\tconst shortfalls = new Map<number, BN>();\n\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\n\tfor (const [\n\t\tmarketIndex,\n\t\tisolatedCalc,\n\t] of marginCalc.isolatedMarginCalculations) {\n\t\tconst shortfall = isolatedCalc.marginShortage();\n\t\tif (shortfall.gt(ZERO)) {\n\t\t\tshortfalls.set(marketIndex, shortfall);\n\t\t}\n\t}\n\n\treturn shortfalls;\n}\n\n/**\n * Computes the initial margin shortfall for a single isolated perp position.\n * Returns the shortfall in QUOTE_PRECISION, or ZERO if no shortfall.\n */\nexport function getIsolatedMarginShortfall(\n\tuser: User,\n\tmarketIndex: number\n): BN {\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\tconst isolatedCalc = marginCalc.isolatedMarginCalculations.get(marketIndex);\n\n\tif (!isolatedCalc) {\n\t\treturn ZERO;\n\t}\n\n\treturn isolatedCalc.marginShortage();\n}\n\n/**\n * Returns all isolated margin shortfalls as an array, excluding a specific market index.\n * Useful for getting shortfalls for \"other\" isolated positions.\n */\nexport function getOtherIsolatedMarginShortfalls(\n\tuser: User,\n\texcludeMarketIndex?: number\n): IsolatedMarginShortfall[] {\n\tconst shortfalls = getIsolatedMarginShortfalls(user);\n\tconst result: IsolatedMarginShortfall[] = [];\n\n\tfor (const [marketIndex, shortfall] of shortfalls) {\n\t\tif (\n\t\t\texcludeMarketIndex !== undefined &&\n\t\t\tmarketIndex === excludeMarketIndex\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push({ marketIndex, shortfall });\n\t}\n\n\treturn result;\n}\n\n/**\n * Computes the total of all isolated margin shortfalls.\n */\nexport function getTotalIsolatedMarginShortfall(\n\tuser: User,\n\texcludeMarketIndex?: number\n): BN {\n\tconst shortfalls = getOtherIsolatedMarginShortfalls(user, excludeMarketIndex);\n\treturn shortfalls.reduce((acc, s) => acc.add(s.shortfall), ZERO);\n}\n\nexport interface ComputeIsolatedPositionDepositParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\t/**\n\t * Optional direction of the order.\n\t * If provided, we will check if the order will increase the position.\n\t * If the order will not increase the position, we will return 0.\n\t */\n\tdirection?: PositionDirection;\n\t/**\n\t * Margin ratio to use for the position (e.g. 2000 for 5x leverage).\n\t */\n\tmarginRatio: number;\n\t/**\n\t * Optional estimated entry price to use for the margin calculation.\n\t */\n\tentryPrice?: BN;\n\t/**\n\t * Number of open high leverage spots available to the user (if any).\n\t * If greater than 0, we will consider the trade as entering high leverage mode.\n\t */\n\tnumOfOpenHighLeverageSpots?: number;\n\t/**\n\t * Optional buffer denominator for the isolated position deposit.\n\t *\n\t * Smaller numbers mean a bigger buffer.\n\t *\n\t * bufferDenominator -> Buffer %\n\t *\n\t * 15 -> 6.67%\n\t *\n\t * 20 (default) -> 5.00%\n\t *\n\t * 50 -> 2.00%\n\t *\n\t * 100 -> 1.00%\n\t *\n\t * 180 -> 0.56%\n\t *\n\t * 200 -> 0.50%\n\t */\n\tbufferDenominator?: number;\n\t/**\n\t * If true, the current market's initial margin shortfall (if any)\n\t * will be added to the deposit amount.\n\t */\n\tincludeExistingShortfall?: boolean;\n\t/**\n\t * Pre-computed existing shortfall for the current market.\n\t * When provided alongside includeExistingShortfall, avoids a redundant getMarginCalculation call.\n\t */\n\texistingShortfall?: BN;\n}\n\n/**\n * Computes the isolated position deposit required for opening an isolated perp position.\n * Returns a BN in QUOTE_PRECISION (USDC).\n */\nexport function computeIsolatedPositionDepositForTrade({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tbaseAssetAmount,\n\tdirection,\n\tmarginRatio,\n\tentryPrice,\n\tnumOfOpenHighLeverageSpots,\n\tbufferDenominator,\n\tincludeExistingShortfall,\n\texistingShortfall: precomputedShortfall,\n}: ComputeIsolatedPositionDepositParams): BN | null {\n\t// Only require isolated deposit if the order will increase the position (when direction is provided)\n\tif (direction !== undefined) {\n\t\tconst maybeOrderParams: OptionalOrderParams = {\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\torderType: OrderType.MARKET,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount,\n\t\t};\n\t\tconst subAccountId = user.getUserAccount().subAccountId;\n\t\tconst isIncreasing = driftClient.isOrderIncreasingPosition(\n\t\t\tmaybeOrderParams,\n\t\t\tsubAccountId\n\t\t);\n\t\tif (!isIncreasing) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tconst userIsInHighLeverageMode = user.isHighLeverageMode('Initial') ?? false;\n\tconst hasOpenHighLeverageSpots =\n\t\tnumOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;\n\tconst enteringHighLeverageMode =\n\t\tuserIsInHighLeverageMode || hasOpenHighLeverageSpots;\n\n\tconst marginRequired = calculateMarginUSDCRequiredForTrade(\n\t\tdriftClient,\n\t\tmarketIndex,\n\t\tbaseAssetAmount,\n\t\tmarginRatio,\n\t\tenteringHighLeverageMode,\n\t\tentryPrice\n\t);\n\n\tlet depositAmount = marginRequired.add(\n\t\tmarginRequired.div(\n\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t)\n\t);\n\n\t// Add existing shortfall for this market if requested\n\tif (includeExistingShortfall) {\n\t\tconst existingShortfall =\n\t\t\tprecomputedShortfall ?? getIsolatedMarginShortfall(user, marketIndex);\n\t\tif (existingShortfall.gt(ZERO)) {\n\t\t\t// Add shortfall with a 5% buffer on top (same as new margin)\n\t\t\tconst shortfallWithBuffer = existingShortfall.add(\n\t\t\t\texistingShortfall.div(\n\t\t\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t\t\t)\n\t\t\t);\n\t\t\tdepositAmount = depositAmount.add(shortfallWithBuffer);\n\t\t}\n\t}\n\n\treturn depositAmount;\n}\n\n/**\n * Error thrown when underwater isolated positions are detected and\n * replenishUnderwaterPositions is not set to true.\n */\nexport class UnderwaterIsolatedPositionsError extends Error {\n\tconstructor(public readonly shortfalls: IsolatedMarginShortfall[]) {\n\t\tsuper(\n\t\t\t`Underwater isolated positions detected for markets: ${shortfalls\n\t\t\t\t.map((s) => s.marketIndex)\n\t\t\t\t.join(', ')}. ` +\n\t\t\t\t`Set replenishUnderwaterPositions: true to auto-cover, or manually handle shortfalls.`\n\t\t);\n\t\tthis.name = 'UnderwaterIsolatedPositionsError';\n\t}\n}\n\n/**\n * Calculates isolated position deposits for a trade.\n * Auto-computes the main deposit from positionMaxLeverage.\n * Also detects underwater positions on other markets and either throws or computes additional deposits.\n */\nexport function calculateIsolatedPositionDeposits(params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\tdirection?: PositionDirection;\n\tpositionMaxLeverage: number;\n\treplenishUnderwaterPositions?: boolean;\n\tnumOfOpenHighLeverageSpots?: number;\n}): {\n\tmainDeposit: BN | undefined;\n\tadditionalIsolatedPositionDeposits:\n\t\t| AdditionalIsolatedPositionDeposit[]\n\t\t| undefined;\n} {\n\t// Compute all shortfalls once (single getMarginCalculation call)\n\t// to avoid duplicate expensive margin calculations\n\tconst allShortfalls = getIsolatedMarginShortfalls(params.user);\n\n\t// Extract current market's shortfall from the pre-computed map\n\tconst currentMarketShortfall = allShortfalls.get(params.marketIndex) ?? ZERO;\n\n\tlet mainIsolatedPositionDeposit: BN | undefined;\n\tconst marginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\tparams.positionMaxLeverage\n\t);\n\n\tif (marginRatio) {\n\t\tmainIsolatedPositionDeposit = computeIsolatedPositionDepositForTrade({\n\t\t\tdriftClient: params.driftClient,\n\t\t\tuser: params.user,\n\t\t\tmarketIndex: params.marketIndex,\n\t\t\tbaseAssetAmount: params.baseAssetAmount,\n\t\t\tdirection: params.direction,\n\t\t\tmarginRatio,\n\t\t\tnumOfOpenHighLeverageSpots: params.numOfOpenHighLeverageSpots,\n\t\t\tbufferDenominator: ISOLATED_POSITION_DEPOSIT_BUFFER_BPS,\n\t\t\tincludeExistingShortfall: true,\n\t\t\t// Use pre-computed shortfall to avoid a second getMarginCalculation call\n\t\t\texistingShortfall: currentMarketShortfall,\n\t\t});\n\t}\n\n\t// Check for underwater positions (excluding current market)\n\tconst otherShortfalls: IsolatedMarginShortfall[] = Array.from(allShortfalls)\n\t\t.filter(([marketIndex]) => marketIndex !== params.marketIndex)\n\t\t.map(([marketIndex, shortfall]) => ({ marketIndex, shortfall }));\n\n\tif (otherShortfalls.length > 0 && !params.replenishUnderwaterPositions) {\n\t\tthrow new UnderwaterIsolatedPositionsError(otherShortfalls);\n\t}\n\n\tlet additionalIsolatedPositionDeposits:\n\t\t| AdditionalIsolatedPositionDeposit[]\n\t\t| undefined;\n\n\tif (otherShortfalls.length > 0 && params.replenishUnderwaterPositions) {\n\t\tadditionalIsolatedPositionDeposits = otherShortfalls.map((shortfall) => {\n\t\t\tconst shortfallWithBuffer = shortfall.shortfall.add(\n\t\t\t\tshortfall.shortfall.div(new BN(ISOLATED_POSITION_DEPOSIT_BUFFER_BPS))\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tmarketIndex: shortfall.marketIndex,\n\t\t\t\tamount: shortfallWithBuffer,\n\t\t\t};\n\t\t});\n\t}\n\n\treturn {\n\t\tmainDeposit: mainIsolatedPositionDeposit,\n\t\tadditionalIsolatedPositionDeposits,\n\t};\n}\n\n/**\n * Resolves isolated position deposits based on margin mode.\n * Returns undefined for cross margin mode, otherwise computes deposits.\n *\n * If marginMode is not explicitly provided, derives it from the user's existing position.\n */\nexport function resolveIsolatedPositionDeposits(params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\tdirection?: PositionDirection;\n\tpositionMaxLeverage: number;\n\tmarginMode?: 'isolated' | 'cross';\n\treplenishUnderwaterPositions?: boolean;\n\tnumOfOpenHighLeverageSpots?: number;\n}): ReturnType<typeof calculateIsolatedPositionDeposits> | undefined {\n\tconst isIsolated =\n\t\t(params.marginMode ??\n\t\t\tgetPositionMarginMode(params.user, params.marketIndex)) === 'isolated';\n\n\tif (!isIsolated) return undefined;\n\n\treturn calculateIsolatedPositionDeposits(params);\n}\n\n/**\n * Resolves isolated position deposits, using pre-computed overrides if provided.\n * When `isolatedPositionDepositsOverride` is provided, skips auto-compute and uses\n * the override values directly. Otherwise, delegates to `resolveIsolatedPositionDeposits()`.\n */\nexport function resolveIsolatedPositionDepositsWithOverride(\n\toverride: IsolatedPositionDepositsOverride | undefined,\n\tcomputeParams: Parameters<typeof resolveIsolatedPositionDeposits>[0]\n): ReturnType<typeof resolveIsolatedPositionDeposits> {\n\tif (override !== undefined) {\n\t\treturn {\n\t\t\tmainDeposit: override.mainDeposit,\n\t\t\tadditionalIsolatedPositionDeposits: override.additionalDeposits,\n\t\t};\n\t}\n\treturn resolveIsolatedPositionDeposits(computeParams);\n}\n\nexport async function getIsolatedPositionDepositIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tisolatedPositionDeposit?: BN,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!isolatedPositionDeposit) {\n\t\treturn undefined;\n\t}\n\tif (isolatedPositionDeposit.isZero()) {\n\t\treturn undefined;\n\t}\n\n\treturn driftClient.getTransferIsolatedPerpPositionDepositIx(\n\t\tisolatedPositionDeposit,\n\t\tmarketIndex,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined, // noAmountBuffer\n\t\tsigningAuthority\n\t);\n}\n"]}
1
+ {"version":3,"file":"isolatedPositionDeposit.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/isolatedPosit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kGAWC;AAEM,KAAK,UAAU,oCAAoC,CACzD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,uBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,uBAAuB,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,WAAW,CAAC,wCAAwC,CAC1D,uBAAuB,EACvB,WAAW,EACX,IAAI,CAAC,cAAc,EAAE,CAAC,YAAY,EAClC,SAAS,EAAE,iBAAiB;IAC5B,gBAAgB,CAChB,CAAC;AACH,CAAC;AArBD,oFAqBC","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tUser,\n\tcalculateMarginUSDCRequiredForTrade,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tMarketType,\n\tOrderType,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { TRADING_UTILS } from '../../../../../_deprecated/trading-utils';\nimport {\n\tAdditionalIsolatedPositionDeposit,\n\tIsolatedPositionDepositsOverride,\n} from './types';\nimport { getPositionMarginMode } from '../../../details/user/positionMarginMode';\n\nexport const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;\n\nexport interface IsolatedMarginShortfall {\n\tmarketIndex: number;\n\tshortfall: BN;\n}\n\n/**\n * Computes the initial margin shortfall for all isolated perp positions.\n * Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).\n * Only includes positions that are under initial margin (shortfall > 0).\n */\nexport function getIsolatedMarginShortfalls(user: User): Map<number, BN> {\n\tconst shortfalls = new Map<number, BN>();\n\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\n\tfor (const [\n\t\tmarketIndex,\n\t\tisolatedCalc,\n\t] of marginCalc.isolatedMarginCalculations) {\n\t\tconst shortfall = isolatedCalc.marginShortage();\n\t\tif (shortfall.gt(ZERO)) {\n\t\t\tshortfalls.set(marketIndex, shortfall);\n\t\t}\n\t}\n\n\treturn shortfalls;\n}\n\n/**\n * Computes the initial margin shortfall for a single isolated perp position.\n * Returns the shortfall in QUOTE_PRECISION, or ZERO if no shortfall.\n */\nexport function getIsolatedMarginShortfall(\n\tuser: User,\n\tmarketIndex: number\n): BN {\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\tconst isolatedCalc = marginCalc.isolatedMarginCalculations.get(marketIndex);\n\n\tif (!isolatedCalc) {\n\t\treturn ZERO;\n\t}\n\n\treturn isolatedCalc.marginShortage();\n}\n\n/**\n * Returns all isolated margin shortfalls as an array, excluding a specific market index.\n * Useful for getting shortfalls for \"other\" isolated positions.\n */\nexport function getOtherIsolatedMarginShortfalls(\n\tuser: User,\n\texcludeMarketIndex?: number\n): IsolatedMarginShortfall[] {\n\tconst shortfalls = getIsolatedMarginShortfalls(user);\n\tconst result: IsolatedMarginShortfall[] = [];\n\n\tfor (const [marketIndex, shortfall] of shortfalls) {\n\t\tif (\n\t\t\texcludeMarketIndex !== undefined &&\n\t\t\tmarketIndex === excludeMarketIndex\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push({ marketIndex, shortfall });\n\t}\n\n\treturn result;\n}\n\n/**\n * Computes the total of all isolated margin shortfalls.\n */\nexport function getTotalIsolatedMarginShortfall(\n\tuser: User,\n\texcludeMarketIndex?: number\n): BN {\n\tconst shortfalls = getOtherIsolatedMarginShortfalls(user, excludeMarketIndex);\n\treturn shortfalls.reduce((acc, s) => acc.add(s.shortfall), ZERO);\n}\n\nexport interface ComputeIsolatedPositionDepositParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\t/**\n\t * Optional direction of the order.\n\t * If provided, we will check if the order will increase the position.\n\t * If the order will not increase the position, we will return 0.\n\t */\n\tdirection?: PositionDirection;\n\t/**\n\t * Margin ratio to use for the position (e.g. 2000 for 5x leverage).\n\t */\n\tmarginRatio: number;\n\t/**\n\t * Optional estimated entry price to use for the margin calculation.\n\t */\n\tentryPrice?: BN;\n\t/**\n\t * Number of open high leverage spots available to the user (if any).\n\t * If greater than 0, we will consider the trade as entering high leverage mode.\n\t */\n\tnumOfOpenHighLeverageSpots?: number;\n\t/**\n\t * Optional buffer denominator for the isolated position deposit.\n\t *\n\t * Smaller numbers mean a bigger buffer.\n\t *\n\t * bufferDenominator -> Buffer %\n\t *\n\t * 15 -> 6.67%\n\t *\n\t * 20 (default) -> 5.00%\n\t *\n\t * 50 -> 2.00%\n\t *\n\t * 100 -> 1.00%\n\t *\n\t * 180 -> 0.56%\n\t *\n\t * 200 -> 0.50%\n\t */\n\tbufferDenominator?: number;\n\t/**\n\t * If true, the current market's initial margin shortfall (if any)\n\t * will be added to the deposit amount.\n\t */\n\tincludeExistingShortfall?: boolean;\n\t/**\n\t * Pre-computed existing shortfall for the current market.\n\t * When provided alongside includeExistingShortfall, avoids a redundant getMarginCalculation call.\n\t */\n\texistingShortfall?: BN;\n}\n\n/**\n * Computes the isolated position deposit required for opening an isolated perp position.\n * Returns a BN in QUOTE_PRECISION (USDC).\n */\nexport function computeIsolatedPositionDepositForTrade({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tbaseAssetAmount,\n\tdirection,\n\tmarginRatio,\n\tentryPrice,\n\tnumOfOpenHighLeverageSpots,\n\tbufferDenominator,\n\tincludeExistingShortfall,\n\texistingShortfall: precomputedShortfall,\n}: ComputeIsolatedPositionDepositParams): BN | null {\n\t// Only require isolated deposit if the order will increase the position (when direction is provided)\n\tif (direction !== undefined) {\n\t\tconst maybeOrderParams: OptionalOrderParams = {\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\torderType: OrderType.MARKET,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount,\n\t\t};\n\t\tconst subAccountId = user.getUserAccount().subAccountId;\n\t\tconst isIncreasing = driftClient.isOrderIncreasingPosition(\n\t\t\tmaybeOrderParams,\n\t\t\tsubAccountId\n\t\t);\n\t\tif (!isIncreasing) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tconst userIsInHighLeverageMode = user.isHighLeverageMode('Initial') ?? false;\n\tconst hasOpenHighLeverageSpots =\n\t\tnumOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;\n\tconst enteringHighLeverageMode =\n\t\tuserIsInHighLeverageMode || hasOpenHighLeverageSpots;\n\n\tconst marginRequired = calculateMarginUSDCRequiredForTrade(\n\t\tdriftClient,\n\t\tmarketIndex,\n\t\tbaseAssetAmount,\n\t\tmarginRatio,\n\t\tenteringHighLeverageMode,\n\t\tentryPrice\n\t);\n\n\tlet depositAmount = marginRequired.add(\n\t\tmarginRequired.div(\n\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t)\n\t);\n\n\t// Add existing shortfall for this market if requested\n\tif (includeExistingShortfall) {\n\t\tconst existingShortfall =\n\t\t\tprecomputedShortfall ?? getIsolatedMarginShortfall(user, marketIndex);\n\t\tif (existingShortfall.gt(ZERO)) {\n\t\t\t// Add shortfall with a 5% buffer on top (same as new margin)\n\t\t\tconst shortfallWithBuffer = existingShortfall.add(\n\t\t\t\texistingShortfall.div(\n\t\t\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t\t\t)\n\t\t\t);\n\t\t\tdepositAmount = depositAmount.add(shortfallWithBuffer);\n\t\t}\n\t}\n\n\treturn depositAmount;\n}\n\n/**\n * Error thrown when underwater isolated positions are detected and\n * replenishUnderwaterPositions is not set to true.\n */\nexport class UnderwaterIsolatedPositionsError extends Error {\n\tconstructor(public readonly shortfalls: IsolatedMarginShortfall[]) {\n\t\tsuper(\n\t\t\t`Underwater isolated positions detected for markets: ${shortfalls\n\t\t\t\t.map((s) => s.marketIndex)\n\t\t\t\t.join(', ')}. ` +\n\t\t\t\t`Set replenishUnderwaterPositions: true to auto-cover, or manually handle shortfalls.`\n\t\t);\n\t\tthis.name = 'UnderwaterIsolatedPositionsError';\n\t}\n}\n\n/**\n * Calculates isolated position deposits for a trade.\n * Auto-computes the main deposit from positionMaxLeverage.\n * Also detects underwater positions on other markets and either throws or computes additional deposits.\n */\nexport function calculateIsolatedPositionDeposits(params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\tdirection?: PositionDirection;\n\tpositionMaxLeverage: number;\n\treplenishUnderwaterPositions?: boolean;\n\tnumOfOpenHighLeverageSpots?: number;\n}): {\n\tmainDeposit: BN | undefined;\n\tadditionalIsolatedPositionDeposits:\n\t\t| AdditionalIsolatedPositionDeposit[]\n\t\t| undefined;\n} {\n\t// Compute all shortfalls once (single getMarginCalculation call)\n\t// to avoid duplicate expensive margin calculations\n\tconst allShortfalls = getIsolatedMarginShortfalls(params.user);\n\n\t// Extract current market's shortfall from the pre-computed map\n\tconst currentMarketShortfall = allShortfalls.get(params.marketIndex) ?? ZERO;\n\n\tlet mainIsolatedPositionDeposit: BN | undefined;\n\tconst marginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\tparams.positionMaxLeverage\n\t);\n\n\tif (marginRatio) {\n\t\tmainIsolatedPositionDeposit = computeIsolatedPositionDepositForTrade({\n\t\t\tdriftClient: params.driftClient,\n\t\t\tuser: params.user,\n\t\t\tmarketIndex: params.marketIndex,\n\t\t\tbaseAssetAmount: params.baseAssetAmount,\n\t\t\tdirection: params.direction,\n\t\t\tmarginRatio,\n\t\t\tnumOfOpenHighLeverageSpots: params.numOfOpenHighLeverageSpots,\n\t\t\tbufferDenominator: ISOLATED_POSITION_DEPOSIT_BUFFER_BPS,\n\t\t\tincludeExistingShortfall: true,\n\t\t\t// Use pre-computed shortfall to avoid a second getMarginCalculation call\n\t\t\texistingShortfall: currentMarketShortfall,\n\t\t});\n\t}\n\n\t// Check for underwater positions (excluding current market)\n\tconst otherShortfalls: IsolatedMarginShortfall[] = Array.from(allShortfalls)\n\t\t.filter(([marketIndex]) => marketIndex !== params.marketIndex)\n\t\t.map(([marketIndex, shortfall]) => ({ marketIndex, shortfall }));\n\n\tif (otherShortfalls.length > 0 && !params.replenishUnderwaterPositions) {\n\t\tthrow new UnderwaterIsolatedPositionsError(otherShortfalls);\n\t}\n\n\tlet additionalIsolatedPositionDeposits:\n\t\t| AdditionalIsolatedPositionDeposit[]\n\t\t| undefined;\n\n\tif (otherShortfalls.length > 0 && params.replenishUnderwaterPositions) {\n\t\tadditionalIsolatedPositionDeposits = otherShortfalls.map((shortfall) => {\n\t\t\tconst shortfallWithBuffer = shortfall.shortfall.add(\n\t\t\t\tshortfall.shortfall.div(new BN(ISOLATED_POSITION_DEPOSIT_BUFFER_BPS))\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tmarketIndex: shortfall.marketIndex,\n\t\t\t\tamount: shortfallWithBuffer,\n\t\t\t};\n\t\t});\n\t}\n\n\treturn {\n\t\tmainDeposit: mainIsolatedPositionDeposit,\n\t\tadditionalIsolatedPositionDeposits,\n\t};\n}\n\n/**\n * Resolves isolated position deposits based on margin mode.\n * Returns undefined for cross margin mode, otherwise computes deposits.\n *\n * If marginMode is not explicitly provided, derives it from the user's existing position.\n */\nexport function resolveIsolatedPositionDeposits(params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\tdirection?: PositionDirection;\n\tpositionMaxLeverage: number;\n\tmarginMode?: 'isolated' | 'cross';\n\treplenishUnderwaterPositions?: boolean;\n\tnumOfOpenHighLeverageSpots?: number;\n}): ReturnType<typeof calculateIsolatedPositionDeposits> | undefined {\n\tconst isIsolated =\n\t\t(params.marginMode ??\n\t\t\tgetPositionMarginMode(params.user, params.marketIndex)) === 'isolated';\n\n\tif (!isIsolated) return undefined;\n\n\treturn calculateIsolatedPositionDeposits(params);\n}\n\n/**\n * Resolves isolated position deposits, using pre-computed overrides if provided.\n * When `isolatedPositionDepositsOverride` is provided, skips auto-compute and uses\n * the override values directly. Otherwise, delegates to `resolveIsolatedPositionDeposits()`.\n */\nexport function resolveIsolatedPositionDepositsWithOverride(\n\toverride: IsolatedPositionDepositsOverride | undefined,\n\tcomputeParams: Parameters<typeof resolveIsolatedPositionDeposits>[0]\n): ReturnType<typeof resolveIsolatedPositionDeposits> {\n\tif (override !== undefined) {\n\t\treturn {\n\t\t\tmainDeposit: override.mainDeposit,\n\t\t\tadditionalIsolatedPositionDeposits: override.additionalDeposits,\n\t\t};\n\t}\n\treturn resolveIsolatedPositionDeposits(computeParams);\n}\n\nexport async function getIsolatedPositionDepositIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tisolatedPositionDeposit?: BN,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!isolatedPositionDeposit) {\n\t\treturn undefined;\n\t}\n\tif (isolatedPositionDeposit.isZero()) {\n\t\treturn undefined;\n\t}\n\n\treturn driftClient.getTransferIsolatedPerpPositionDepositIx(\n\t\tisolatedPositionDeposit,\n\t\tmarketIndex,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined, // noAmountBuffer\n\t\tsigningAuthority\n\t);\n}\n"]}
@@ -2,7 +2,7 @@ import { DriftClient, User, BN, PositionDirection, ReferrerInfo, OrderType } fro
2
2
  import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
3
3
  import { SwiftOrderOptions, SwiftOrderMessage } from '../openSwiftOrder';
4
4
  import { OptionalAuctionParamsRequestInputs } from '../dlobServer';
5
- import { HighLeverageOptions } from '../../../../../../common-ui-utils/order';
5
+ import { HighLeverageOptions } from '../../../../../../utils/orders';
6
6
  import { WithTxnParams } from '../../../../types';
7
7
  import { TxnOrSwiftResult, IsolatedPositionDepositsOverride } from '../types';
8
8
  import { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';
@@ -6,7 +6,7 @@ const utils_1 = require("../../../../../../utils");
6
6
  const openSwiftOrder_1 = require("../openSwiftOrder");
7
7
  const orderParams_1 = require("../../../../../utils/orderParams");
8
8
  const dlobServer_1 = require("../dlobServer");
9
- const order_1 = require("../../../../../../common-ui-utils/order");
9
+ const order_utils_1 = require("../../../../../../_deprecated/order-utils");
10
10
  const errors_1 = require("../../../../../Drift/constants/errors");
11
11
  const positionMaxLeverage_1 = require("../positionMaxLeverage");
12
12
  const isolatedPositionDeposit_1 = require("../isolatedPositionDeposit");
@@ -32,7 +32,7 @@ async function prepSwiftMarketOrderData(params) {
32
32
  reduceOnly,
33
33
  onAuctionParamsFetched: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onAuctionParamsFetched,
34
34
  });
35
- const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
35
+ const bitFlags = order_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
36
36
  const orderParams = {
37
37
  ...fetchedOrderParams,
38
38
  userOrderId,
@@ -144,7 +144,7 @@ const createPlaceAndTakePerpMarketOrderIx = async ({ assetType, direction, dlobS
144
144
  limit: 4,
145
145
  }),
146
146
  ]);
147
- const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
147
+ const bitFlags = order_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
148
148
  fetchedOrderParams.bitFlags = bitFlags;
149
149
  fetchedOrderParams.userOrderId = userOrderId;
150
150
  if (orderType) {
@@ -268,7 +268,7 @@ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, mark
268
268
  reduceOnly,
269
269
  onAuctionParamsFetched: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onAuctionParamsFetched,
270
270
  });
271
- const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
271
+ const bitFlags = order_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
272
272
  const orderParams = {
273
273
  ...fetchedOrderParams,
274
274
  userOrderId,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,mDAAqD;AACrD,sDAK2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,mEAGiD;AAGjD,kEAAyE;AAEzE,gEAA0E;AAE1E,wEAGoC;AAoGpC;;;GAGG;AACH,KAAK,UAAU,wBAAwB,CAAC,MAAqC;IAC5E,MAAM,EACL,WAAW,EACX,IAAI,EACJ,SAAS,EACT,WAAW,EACX,SAAS,EACT,MAAM,EACN,UAAU,EACV,iBAAiB,EACjB,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,EACnB,WAAW,GAAG,CAAC,EACf,SAAS,GACT,GAAG,MAAM,CAAC;IAEX,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACrD,CAAC;IAED,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;QAC3B,UAAU;QACV,sBAAsB,EAAE,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,sBAAsB;KACzD,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,0BAAkB,CAAC,0BAA0B,CAC7D,WAAW,EACX,WAAW,EACX,IAAI,EACJ,mBAAmB,EACnB,mBAAmB,C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AAsB,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\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tprepSwiftOrderMessage,\n\tSwiftOrderOptions,\n\tSwiftOrderMessage,\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, IsolatedPositionDepositsOverride } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { AuctionParamsFetchedCallback } from '../../../../../utils/auctionParamsResponseMapper';\nimport {\n\tgetIsolatedPositionDepositIxIfNeeded,\n\tresolveIsolatedPositionDepositsWithOverride,\n} from '../isolatedPositionDeposit';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\treduceOnly?: boolean;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Optional per-market leverage to set for this position.\n\t * If provided and different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\t/**\n\t * Position margin mode to use for the order.\n\t * When 'isolated', auto-computes isolated position deposit from positionMaxLeverage,\n\t * and any additional isolated position deposits need to replenish under-collateralized positions.\n\t * If not provided, the position margin mode will be derived from the user's position margin mode,\n\t * and if that does not exist, it will default to 'cross'.\n\t */\n\tmarginMode?: 'isolated' | 'cross';\n\t/**\n\t * Pre-computed isolated position deposits override. When provided,\n\t * skips auto-compute and uses these values directly.\n\t */\n\tisolatedPositionDepositsOverride?: IsolatedPositionDepositsOverride;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n\tcallbacks?: {\n\t\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Shared prep logic for swift market orders: validates input, fetches auction params,\n * computes bit flags, and resolves the user account.\n */\nasync function prepSwiftMarketOrderData(params: OpenPerpMarketOrderBaseParams) {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tdirection,\n\t\tamount,\n\t\treduceOnly,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions,\n\t\tuserOrderId = 0,\n\t\tcallbacks,\n\t} = params;\n\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t\treduceOnly,\n\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t});\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\n\treturn { userAccount, orderParams };\n}\n\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder(\n\tparams: OpenPerpMarketOrderBaseParamsWithSwift\n): Promise<void> {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tamount,\n\t\tdirection,\n\t\tbracketOrders,\n\t\tswiftOptions,\n\t\tpositionMaxLeverage,\n\t\tmarginMode,\n\t\thighLeverageOptions,\n\t\tbuilderParams,\n\t} = params;\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: amount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits. Will throw error if other isolated position shortfalls exists.\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst { userAccount, orderParams } = await prepSwiftMarketOrderData(params);\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\nexport type CreateSwiftMarketOrderMessageParams = Omit<\n\tOpenPerpMarketOrderBaseParams,\n\t'placeAndTake' | 'mainSignerOverride'\n> & {\n\tisDelegate?: boolean;\n\tuserSigningSlotBuffer?: number;\n};\n\n/**\n * Prepares a Swift market order message without signing or sending it.\n * Fetches auction params from the DLOB server and creates the prepared message.\n *\n * @returns The prepared SwiftOrderMessage ready for client-side signing and sending\n */\nexport async function createSwiftMarketOrderMessage(\n\tparams: CreateSwiftMarketOrderMessageParams\n): Promise<SwiftOrderMessage> {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tamount,\n\t\tdirection,\n\t\tbracketOrders,\n\t\tpositionMaxLeverage,\n\t\tmarginMode,\n\t\thighLeverageOptions,\n\t\tbuilderParams,\n\t\tisDelegate = false,\n\t\tuserSigningSlotBuffer,\n\t} = params;\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: amount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits. Will throw error if other isolated position shortfalls exists.\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst { userAccount, orderParams } = await prepSwiftMarketOrderData(params);\n\n\treturn prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\torderType,\n\tprice,\n\treduceOnly,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tpositionMaxLeverage,\n\tcallbacks,\n}: Omit<\n\tOpenPerpMarketOrderBaseParams,\n\t'marginMode' | 'isolatedPositionDepositsOverride'\n> & {\n\torderType?: OrderType;\n\tprice?: BN;\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n\thighLeverageOptions?: HighLeverageOptions;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\treduceOnly,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (orderType) {\n\t\tfetchedOrderParams.orderType = orderType;\n\t}\n\n\tif (price) {\n\t\tfetchedOrderParams.price = price;\n\t\tfetchedOrderParams.auctionEndPrice = price;\n\t}\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * adds an instruction to update the position's maxMarginRatio before placing the order.\n * @param userOrderId - the order ID in terms of incremental fills (usually 0). do NOT use the nextOrderId from the user account. values over 255 will cause the order to fail onchain.\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\treduceOnly,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n\tpositionMaxLeverage,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tmarginMode,\n\tisolatedPositionDepositsOverride,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tisolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: amount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: true,\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst mainIsolatedDeposit = resolvedDeposits?.mainDeposit;\n\tconst resolvedAdditionalDeposits =\n\t\tresolvedDeposits?.additionalIsolatedPositionDeposits;\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// Fetch all deposit/leverage ixs in parallel\n\tconst [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] =\n\t\tawait Promise.all([\n\t\t\tgetPositionMaxLeverageIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t\tresolvedAdditionalDeposits?.length\n\t\t\t\t? Promise.all(\n\t\t\t\t\t\tresolvedAdditionalDeposits.map((deposit) =>\n\t\t\t\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\t\t\t\tdriftClient,\n\t\t\t\t\t\t\t\tuser,\n\t\t\t\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\t\t\t\tdeposit.amount,\n\t\t\t\t\t\t\t\tmainSignerOverride\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Promise.resolve([] as (TransactionInstruction | undefined)[]),\n\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tmainIsolatedDeposit,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t]);\n\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\tfor (const ix of additionalDepositIxs) {\n\t\tif (ix) {\n\t\t\tallIxs.push(ix);\n\t\t}\n\t}\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\n\t}\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treduceOnly,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t\tmainSignerOverride,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\treduceOnly,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t});\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\n\t\t\thighLeverageOptions\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\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,sDAK2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,2EAA+E;AAI/E,kEAAyE;AAEzE,gEAA0E;AAE1E,wEAGoC;AAoGpC;;;GAGG;AACH,KAAK,UAAU,wBAAwB,CAAC,MAAqC;IAC5E,MAAM,EACL,WAAW,EACX,IAAI,EACJ,SAAS,EACT,WAAW,EACX,SAAS,EACT,MAAM,EACN,UAAU,EACV,iBAAiB,EACjB,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,EACnB,WAAW,GAAG,CAAC,EACf,SAAS,GACT,GAAG,MAAM,CAAC;IAEX,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACrD,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACxD,WAAW;QACX,IAAI;QACJ,SAAS;QACT,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT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,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\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tprepSwiftOrderMessage,\n\tSwiftOrderOptions,\n\tSwiftOrderMessage,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport { ORDER_COMMON_UTILS } from '../../../../../../_deprecated/order-utils';\nimport { HighLeverageOptions } from '../../../../../../utils/orders';\nimport { WithTxnParams } from '../../../../types';\nimport { TxnOrSwiftResult, IsolatedPositionDepositsOverride } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { AuctionParamsFetchedCallback } from '../../../../../utils/auctionParamsResponseMapper';\nimport {\n\tgetIsolatedPositionDepositIxIfNeeded,\n\tresolveIsolatedPositionDepositsWithOverride,\n} from '../isolatedPositionDeposit';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\treduceOnly?: boolean;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Optional per-market leverage to set for this position.\n\t * If provided and different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\t/**\n\t * Position margin mode to use for the order.\n\t * When 'isolated', auto-computes isolated position deposit from positionMaxLeverage,\n\t * and any additional isolated position deposits need to replenish under-collateralized positions.\n\t * If not provided, the position margin mode will be derived from the user's position margin mode,\n\t * and if that does not exist, it will default to 'cross'.\n\t */\n\tmarginMode?: 'isolated' | 'cross';\n\t/**\n\t * Pre-computed isolated position deposits override. When provided,\n\t * skips auto-compute and uses these values directly.\n\t */\n\tisolatedPositionDepositsOverride?: IsolatedPositionDepositsOverride;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n\tcallbacks?: {\n\t\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Shared prep logic for swift market orders: validates input, fetches auction params,\n * computes bit flags, and resolves the user account.\n */\nasync function prepSwiftMarketOrderData(params: OpenPerpMarketOrderBaseParams) {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tdirection,\n\t\tamount,\n\t\treduceOnly,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions,\n\t\tuserOrderId = 0,\n\t\tcallbacks,\n\t} = params;\n\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t\treduceOnly,\n\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t});\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\n\treturn { userAccount, orderParams };\n}\n\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder(\n\tparams: OpenPerpMarketOrderBaseParamsWithSwift\n): Promise<void> {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tamount,\n\t\tdirection,\n\t\tbracketOrders,\n\t\tswiftOptions,\n\t\tpositionMaxLeverage,\n\t\tmarginMode,\n\t\thighLeverageOptions,\n\t\tbuilderParams,\n\t} = params;\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: amount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits. Will throw error if other isolated position shortfalls exists.\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst { userAccount, orderParams } = await prepSwiftMarketOrderData(params);\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\nexport type CreateSwiftMarketOrderMessageParams = Omit<\n\tOpenPerpMarketOrderBaseParams,\n\t'placeAndTake' | 'mainSignerOverride'\n> & {\n\tisDelegate?: boolean;\n\tuserSigningSlotBuffer?: number;\n};\n\n/**\n * Prepares a Swift market order message without signing or sending it.\n * Fetches auction params from the DLOB server and creates the prepared message.\n *\n * @returns The prepared SwiftOrderMessage ready for client-side signing and sending\n */\nexport async function createSwiftMarketOrderMessage(\n\tparams: CreateSwiftMarketOrderMessageParams\n): Promise<SwiftOrderMessage> {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tamount,\n\t\tdirection,\n\t\tbracketOrders,\n\t\tpositionMaxLeverage,\n\t\tmarginMode,\n\t\thighLeverageOptions,\n\t\tbuilderParams,\n\t\tisDelegate = false,\n\t\tuserSigningSlotBuffer,\n\t} = params;\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: amount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits. Will throw error if other isolated position shortfalls exists.\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst { userAccount, orderParams } = await prepSwiftMarketOrderData(params);\n\n\treturn prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage,\n\t\t\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\n\t\t},\n\t\tbuilderParams,\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\torderType,\n\tprice,\n\treduceOnly,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tpositionMaxLeverage,\n\tcallbacks,\n}: Omit<\n\tOpenPerpMarketOrderBaseParams,\n\t'marginMode' | 'isolatedPositionDepositsOverride'\n> & {\n\torderType?: OrderType;\n\tprice?: BN;\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n\thighLeverageOptions?: HighLeverageOptions;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\treduceOnly,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\tpositionMaxLeverage,\n\t\thighLeverageOptions\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (orderType) {\n\t\tfetchedOrderParams.orderType = orderType;\n\t}\n\n\tif (price) {\n\t\tfetchedOrderParams.price = price;\n\t\tfetchedOrderParams.auctionEndPrice = price;\n\t}\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param positionMaxLeverage - Optional per-market leverage (e.g., 5 for 5x). If provided and different from current,\n * adds an instruction to update the position's maxMarginRatio before placing the order.\n * @param userOrderId - the order ID in terms of incremental fills (usually 0). do NOT use the nextOrderId from the user account. values over 255 will cause the order to fail onchain.\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\treduceOnly,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n\tpositionMaxLeverage,\n\tmainSignerOverride,\n\thighLeverageOptions,\n\tmarginMode,\n\tisolatedPositionDepositsOverride,\n\tcallbacks,\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tisolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: amount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: true,\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst mainIsolatedDeposit = resolvedDeposits?.mainDeposit;\n\tconst resolvedAdditionalDeposits =\n\t\tresolvedDeposits?.additionalIsolatedPositionDeposits;\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// Fetch all deposit/leverage ixs in parallel\n\tconst [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] =\n\t\tawait Promise.all([\n\t\t\tgetPositionMaxLeverageIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t\tresolvedAdditionalDeposits?.length\n\t\t\t\t? Promise.all(\n\t\t\t\t\t\tresolvedAdditionalDeposits.map((deposit) =>\n\t\t\t\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\t\t\t\tdriftClient,\n\t\t\t\t\t\t\t\tuser,\n\t\t\t\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\t\t\t\tdeposit.amount,\n\t\t\t\t\t\t\t\tmainSignerOverride\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Promise.resolve([] as (TransactionInstruction | undefined)[]),\n\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tmainIsolatedDeposit,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t]);\n\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\tfor (const ix of additionalDepositIxs) {\n\t\tif (ix) {\n\t\t\tallIxs.push(ix);\n\t\t}\n\t}\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\n\t}\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treduceOnly,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t\tmainSignerOverride,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t\treduceOnly,\n\t\t\tonAuctionParamsFetched: callbacks?.onAuctionParamsFetched,\n\t\t});\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\n\t\t\thighLeverageOptions\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\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,7 +1,7 @@
1
1
  import { DriftClient, User, BN, PostOnlyParams } from '@drift-labs/sdk';
2
2
  import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
3
3
  import { SwiftOrderOptions, SwiftOrderMessage } from '../openSwiftOrder';
4
- import { HighLeverageOptions } from '../../../../../../common-ui-utils';
4
+ import { HighLeverageOptions } from '../../../../../../utils/orders';
5
5
  import { TxnOrSwiftResult, LimitOrderParamsOrderConfig, NonMarketOrderParamsConfig, IsolatedPositionDepositsOverride } from '../types';
6
6
  import { WithTxnParams } from '../../../../types';
7
7
  export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {