@drift-labs/common 1.0.47 → 1.0.49

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 (25) hide show
  1. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -4
  2. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  3. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +4 -2
  4. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
  5. package/lib/drift/Drift/clients/CentralServerDrift/index.js +3 -2
  6. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  7. package/lib/drift/Drift/clients/CentralServerDrift/types.d.ts +8 -10
  8. package/lib/drift/Drift/clients/CentralServerDrift/types.js.map +1 -1
  9. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.d.ts +56 -1
  10. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +102 -4
  11. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
  12. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +13 -12
  13. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +51 -17
  14. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  15. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +14 -7
  16. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +56 -23
  17. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  18. package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +10 -6
  19. package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
  20. package/lib/drift/base/details/user/positionMarginMode.d.ts +8 -0
  21. package/lib/drift/base/details/user/positionMarginMode.js +18 -0
  22. package/lib/drift/base/details/user/positionMarginMode.js.map +1 -0
  23. package/lib/drift/utils/orderParams.d.ts +1 -1
  24. package/lib/drift/utils/orderParams.js.map +1 -1
  25. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"isolatedPositionDeposit.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAGZ,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,EAAE,CAAC;QACnB,OAAO,UAAI,CAAC;IACb,CAAC;IAED,OAAO,YAAY,CAAC,cAAc,EAAE,CAAC;AACtC,CAAC;AAZD,gEAYC;AAED;;;GAGG;AACH,SAAgB,gCAAgC,CAC/C,IAAU,EACV,kBAA2B;IAE3B,MAAM,UAAU,GA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O,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';\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}\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}: 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); // buffer in basis points\n\n\t// Add existing shortfall for this market if requested\n\tif (includeExistingShortfall) {\n\t\tconst existingShortfall = 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\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/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,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tC,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"]}
@@ -4,8 +4,8 @@ import { SwiftOrderOptions, SwiftOrderMessage } from '../openSwiftOrder';
4
4
  import { OptionalAuctionParamsRequestInputs } from '../dlobServer';
5
5
  import { HighLeverageOptions } from '../../../../../../common-ui-utils/order';
6
6
  import { WithTxnParams } from '../../../../types';
7
- import { TxnOrSwiftResult } from '../types';
8
- import { PlaceAndTakeParams, OptionalTriggerOrderParams, AdditionalIsolatedPositionDeposit } from '../types';
7
+ import { TxnOrSwiftResult, IsolatedPositionDepositsOverride } from '../types';
8
+ import { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';
9
9
  import { AuctionParamsFetchedCallback } from '../../../../../utils/auctionParamsResponseMapper';
10
10
  export interface OpenPerpMarketOrderBaseParams {
11
11
  driftClient: DriftClient;
@@ -31,17 +31,18 @@ export interface OpenPerpMarketOrderBaseParams {
31
31
  */
32
32
  positionMaxLeverage: number;
33
33
  /**
34
- * Optional isolated position deposit amount.
35
- * If provided, it will be added to the order params as isolatedPositionDeposit.
36
- * This field is used for opening isolated positions.
34
+ * Position margin mode to use for the order.
35
+ * When 'isolated', auto-computes isolated position deposit from positionMaxLeverage,
36
+ * and any additional isolated position deposits need to replenish under-collateralized positions.
37
+ * If not provided, the position margin mode will be derived from the user's position margin mode,
38
+ * and if that does not exist, it will default to 'cross'.
37
39
  */
38
- isolatedPositionDeposit?: BN;
40
+ marginMode?: 'isolated' | 'cross';
39
41
  /**
40
- * Additional isolated position deposits needed to top up other
41
- * under-collateralized isolated positions before placing the order.
42
- * Each deposit will create a separate instruction.
42
+ * Pre-computed isolated position deposits override. When provided,
43
+ * skips auto-compute and uses these values directly.
43
44
  */
44
- additionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];
45
+ isolatedPositionDepositsOverride?: IsolatedPositionDepositsOverride;
45
46
  /**
46
47
  * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.
47
48
  * This is only applicable for non-SWIFT orders.
@@ -111,7 +112,7 @@ export declare function createSwiftMarketOrderMessage(params: CreateSwiftMarketO
111
112
  * Creates a placeAndTake transaction instruction.
112
113
  * Fallbacks to a regular market order if no top makers are found.
113
114
  */
114
- export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, orderType, price, reduceOnly, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, mainSignerOverride, highLeverageOptions, positionMaxLeverage, callbacks, }: OpenPerpMarketOrderBaseParams & {
115
+ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, direction, dlobServerHttpUrl, marketIndex, driftClient, user, userOrderId, amount, orderType, price, reduceOnly, referrerInfo, auctionDurationPercentage, optionalAuctionParamsInputs, mainSignerOverride, highLeverageOptions, positionMaxLeverage, callbacks, }: Omit<OpenPerpMarketOrderBaseParams, 'marginMode' | 'isolatedPositionDepositsOverride'> & {
115
116
  orderType?: OrderType;
116
117
  price?: BN;
117
118
  direction: PositionDirection;
@@ -140,7 +141,7 @@ export declare const createPlaceAndTakePerpMarketOrderIx: ({ assetType, directio
140
141
  * @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.
141
142
  * @returns Promise resolving to an array of transaction instructions for regular orders
142
143
  */
143
- export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, positionMaxLeverage, mainSignerOverride, highLeverageOptions, isolatedPositionDeposit, additionalIsolatedPositionDeposits, callbacks, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
144
+ export declare const createOpenPerpMarketOrderIxs: ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs, positionMaxLeverage, mainSignerOverride, highLeverageOptions, marginMode, isolatedPositionDepositsOverride, callbacks, }: OpenPerpMarketOrderBaseParams) => Promise<TransactionInstruction[]>;
144
145
  /**
145
146
  * Creates a complete transaction for opening a perp market order.
146
147
  *
@@ -45,7 +45,18 @@ async function prepSwiftMarketOrderData(params) {
45
45
  * Creates and submits a Swift (signed message) order. Only available for perp orders.
46
46
  */
47
47
  async function createSwiftMarketOrder(params) {
48
- const { driftClient, user, marketIndex, bracketOrders, swiftOptions, positionMaxLeverage, isolatedPositionDeposit, builderParams, } = params;
48
+ const { driftClient, user, marketIndex, amount, direction, bracketOrders, swiftOptions, positionMaxLeverage, marginMode, highLeverageOptions, builderParams, } = params;
49
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(params.isolatedPositionDepositsOverride, {
50
+ driftClient,
51
+ user,
52
+ marketIndex,
53
+ baseAssetAmount: amount,
54
+ direction,
55
+ positionMaxLeverage,
56
+ marginMode,
57
+ replenishUnderwaterPositions: false, // Swift doesn't support additional deposits. Will throw error if other isolated position shortfalls exists.
58
+ numOfOpenHighLeverageSpots: highLeverageOptions === null || highLeverageOptions === void 0 ? void 0 : highLeverageOptions.numOfOpenHighLeverageSpots,
59
+ });
49
60
  const { userAccount, orderParams } = await prepSwiftMarketOrderData(params);
50
61
  await (0, openSwiftOrder_1.prepSignAndSendSwiftOrder)({
51
62
  driftClient,
@@ -59,7 +70,7 @@ async function createSwiftMarketOrder(params) {
59
70
  takeProfit: bracketOrders === null || bracketOrders === void 0 ? void 0 : bracketOrders.takeProfit,
60
71
  stopLoss: bracketOrders === null || bracketOrders === void 0 ? void 0 : bracketOrders.stopLoss,
61
72
  positionMaxLeverage,
62
- isolatedPositionDeposit,
73
+ isolatedPositionDeposit: resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit,
63
74
  },
64
75
  builderParams,
65
76
  });
@@ -72,7 +83,18 @@ exports.createSwiftMarketOrder = createSwiftMarketOrder;
72
83
  * @returns The prepared SwiftOrderMessage ready for client-side signing and sending
73
84
  */
74
85
  async function createSwiftMarketOrderMessage(params) {
75
- const { driftClient, user, marketIndex, bracketOrders, positionMaxLeverage, isolatedPositionDeposit, builderParams, isDelegate = false, userSigningSlotBuffer, } = params;
86
+ const { driftClient, user, marketIndex, amount, direction, bracketOrders, positionMaxLeverage, marginMode, highLeverageOptions, builderParams, isDelegate = false, userSigningSlotBuffer, } = params;
87
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(params.isolatedPositionDepositsOverride, {
88
+ driftClient,
89
+ user,
90
+ marketIndex,
91
+ baseAssetAmount: amount,
92
+ direction,
93
+ positionMaxLeverage,
94
+ marginMode,
95
+ replenishUnderwaterPositions: false, // Swift doesn't support additional deposits. Will throw error if other isolated position shortfalls exists.
96
+ numOfOpenHighLeverageSpots: highLeverageOptions === null || highLeverageOptions === void 0 ? void 0 : highLeverageOptions.numOfOpenHighLeverageSpots,
97
+ });
76
98
  const { userAccount, orderParams } = await prepSwiftMarketOrderData(params);
77
99
  return (0, openSwiftOrder_1.prepSwiftOrderMessage)({
78
100
  driftClient,
@@ -86,7 +108,7 @@ async function createSwiftMarketOrderMessage(params) {
86
108
  takeProfit: bracketOrders === null || bracketOrders === void 0 ? void 0 : bracketOrders.takeProfit,
87
109
  stopLoss: bracketOrders === null || bracketOrders === void 0 ? void 0 : bracketOrders.stopLoss,
88
110
  positionMaxLeverage,
89
- isolatedPositionDeposit,
111
+ isolatedPositionDeposit: resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit,
90
112
  },
91
113
  builderParams,
92
114
  });
@@ -163,28 +185,42 @@ exports.createPlaceAndTakePerpMarketOrderIx = createPlaceAndTakePerpMarketOrderI
163
185
  * @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.
164
186
  * @returns Promise resolving to an array of transaction instructions for regular orders
165
187
  */
166
- const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs = {}, positionMaxLeverage, mainSignerOverride, highLeverageOptions, isolatedPositionDeposit, additionalIsolatedPositionDeposits, callbacks, }) => {
188
+ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, marketIndex, direction, amount, reduceOnly, bracketOrders, dlobServerHttpUrl, placeAndTake, userOrderId, optionalAuctionParamsInputs = {}, positionMaxLeverage, mainSignerOverride, highLeverageOptions, marginMode, isolatedPositionDepositsOverride, callbacks, }) => {
167
189
  var _a, _b, _c, _d;
168
190
  if (!amount || amount.isZero()) {
169
191
  throw new Error('Amount must be greater than zero');
170
192
  }
193
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(isolatedPositionDepositsOverride, {
194
+ driftClient,
195
+ user,
196
+ marketIndex,
197
+ baseAssetAmount: amount,
198
+ direction,
199
+ positionMaxLeverage,
200
+ marginMode,
201
+ replenishUnderwaterPositions: true,
202
+ numOfOpenHighLeverageSpots: highLeverageOptions === null || highLeverageOptions === void 0 ? void 0 : highLeverageOptions.numOfOpenHighLeverageSpots,
203
+ });
204
+ const mainIsolatedDeposit = resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit;
205
+ const resolvedAdditionalDeposits = resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.additionalIsolatedPositionDeposits;
171
206
  const allOrders = [];
172
207
  const allIxs = [];
173
- const leverageIx = await (0, positionMaxLeverage_1.getPositionMaxLeverageIxIfNeeded)(driftClient, user, marketIndex, positionMaxLeverage, mainSignerOverride);
208
+ // Fetch all deposit/leverage ixs in parallel
209
+ const [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] = await Promise.all([
210
+ (0, positionMaxLeverage_1.getPositionMaxLeverageIxIfNeeded)(driftClient, user, marketIndex, positionMaxLeverage, mainSignerOverride),
211
+ (resolvedAdditionalDeposits === null || resolvedAdditionalDeposits === void 0 ? void 0 : resolvedAdditionalDeposits.length)
212
+ ? Promise.all(resolvedAdditionalDeposits.map((deposit) => (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, deposit.marketIndex, deposit.amount, mainSignerOverride)))
213
+ : Promise.resolve([]),
214
+ (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, mainIsolatedDeposit, mainSignerOverride),
215
+ ]);
174
216
  if (leverageIx) {
175
217
  allIxs.push(leverageIx);
176
218
  }
177
- // Add additional isolated position deposit ixs for other under-collateralized positions
178
- if (additionalIsolatedPositionDeposits === null || additionalIsolatedPositionDeposits === void 0 ? void 0 : additionalIsolatedPositionDeposits.length) {
179
- const additionalDepositIxPromises = additionalIsolatedPositionDeposits.map((deposit) => (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, deposit.marketIndex, deposit.amount, mainSignerOverride));
180
- const additionalDepositIxs = await Promise.all(additionalDepositIxPromises);
181
- for (const ix of additionalDepositIxs) {
182
- if (ix) {
183
- allIxs.push(ix);
184
- }
219
+ for (const ix of additionalDepositIxs) {
220
+ if (ix) {
221
+ allIxs.push(ix);
185
222
  }
186
223
  }
187
- const isolatedPositionDepositIx = await (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, isolatedPositionDeposit, mainSignerOverride);
188
224
  if (isolatedPositionDepositIx) {
189
225
  allIxs.push(isolatedPositionDepositIx);
190
226
  }
@@ -255,7 +291,6 @@ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, mark
255
291
  limitPrice: bracketOrders.takeProfit.limitPrice,
256
292
  },
257
293
  reduceOnly: (_b = bracketOrders.takeProfit.reduceOnly) !== null && _b !== void 0 ? _b : true,
258
- positionMaxLeverage,
259
294
  });
260
295
  allOrders.push(takeProfitParams);
261
296
  }
@@ -271,7 +306,6 @@ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, mark
271
306
  limitPrice: bracketOrders.stopLoss.limitPrice,
272
307
  },
273
308
  reduceOnly: (_d = bracketOrders.stopLoss.reduceOnly) !== null && _d !== void 0 ? _d : true,
274
- positionMaxLeverage,
275
309
  });
276
310
  allOrders.push(stopLossParams);
277
311
  }
@@ -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;AAMzE,gEAA0E;AAE1E,wEAAkF;AAmGlF;;;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,C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OptionalOrderParams,\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 } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport {\n\tPlaceAndTakeParams,\n\tOptionalTriggerOrderParams,\n\tAdditionalIsolatedPositionDeposit,\n} from '../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { AuctionParamsFetchedCallback } from '../../../../../utils/auctionParamsResponseMapper';\nimport { getIsolatedPositionDepositIxIfNeeded } 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 * Optional isolated position deposit amount.\n\t * If provided, it will be added to the order params as isolatedPositionDeposit.\n\t * This field is used for opening isolated positions.\n\t */\n\tisolatedPositionDeposit?: BN;\n\t/**\n\t * Additional isolated position deposits needed to top up other\n\t * under-collateralized isolated positions before placing the order.\n\t * Each deposit will create a separate instruction.\n\t */\n\tadditionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];\n\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\tbracketOrders,\n\t\tswiftOptions,\n\t\tpositionMaxLeverage,\n\t\tisolatedPositionDeposit,\n\t\tbuilderParams,\n\t} = params;\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,\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\tbracketOrders,\n\t\tpositionMaxLeverage,\n\t\tisolatedPositionDeposit,\n\t\tbuilderParams,\n\t\tisDelegate = false,\n\t\tuserSigningSlotBuffer,\n\t} = params;\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,\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}: OpenPerpMarketOrderBaseParams & {\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\tisolatedPositionDeposit,\n\tadditionalIsolatedPositionDeposits,\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 allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage,\n\t\tmainSignerOverride\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\t// Add additional isolated position deposit ixs for other under-collateralized positions\n\tif (additionalIsolatedPositionDeposits?.length) {\n\t\tconst additionalDepositIxPromises = additionalIsolatedPositionDeposits.map(\n\t\t\t(deposit) =>\n\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\tdeposit.amount,\n\t\t\t\t\tmainSignerOverride\n\t\t\t\t)\n\t\t);\n\t\tconst additionalDepositIxs = await Promise.all(additionalDepositIxPromises);\n\t\tfor (const ix of additionalDepositIxs) {\n\t\t\tif (ix) {\n\t\t\t\tallIxs.push(ix);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst isolatedPositionDepositIx = await getIsolatedPositionDepositIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tisolatedPositionDeposit,\n\t\tmainSignerOverride\n\t);\n\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\tpositionMaxLeverage,\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\tpositionMaxLeverage,\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,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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Type,\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"]}
@@ -2,7 +2,7 @@ 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
4
  import { HighLeverageOptions } from '../../../../../../common-ui-utils';
5
- import { TxnOrSwiftResult, LimitOrderParamsOrderConfig, NonMarketOrderParamsConfig, AdditionalIsolatedPositionDeposit } from '../types';
5
+ import { TxnOrSwiftResult, LimitOrderParamsOrderConfig, NonMarketOrderParamsConfig, IsolatedPositionDepositsOverride } from '../types';
6
6
  import { WithTxnParams } from '../../../../types';
7
7
  export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {
8
8
  driftClient: DriftClient;
@@ -13,6 +13,19 @@ export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderPar
13
13
  reduceOnly?: boolean;
14
14
  postOnly?: PostOnlyParams;
15
15
  userOrderId?: number;
16
+ /**
17
+ * Position margin mode to use for the order.
18
+ * When 'isolated', auto-computes isolated position deposit from positionMaxLeverage,
19
+ * and any additional isolated position deposits need to replenish under-collateralized positions.
20
+ * If not provided, the position margin mode will be derived from the user's position margin mode,
21
+ * and if that does not exist, it will default to 'cross'.
22
+ */
23
+ marginMode?: 'isolated' | 'cross';
24
+ /**
25
+ * Pre-computed isolated position deposits override. When provided,
26
+ * skips auto-compute and uses these values directly.
27
+ */
28
+ isolatedPositionDepositsOverride?: IsolatedPositionDepositsOverride;
16
29
  autoEnterHighLeverageModeBufferPct?: number;
17
30
  /**
18
31
  * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.
@@ -28,12 +41,6 @@ export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderPar
28
41
  builderFeeTenthBps: number;
29
42
  };
30
43
  highLeverageOptions?: HighLeverageOptions;
31
- /**
32
- * Additional isolated position deposits needed to top up other
33
- * under-collateralized isolated positions before placing the order.
34
- * Each deposit will create a separate instruction.
35
- */
36
- additionalIsolatedPositionDeposits?: AdditionalIsolatedPositionDeposit[];
37
44
  }
38
45
  export interface OpenPerpNonMarketOrderParamsWithSwift extends OpenPerpNonMarketOrderBaseParams {
39
46
  swiftOptions: SwiftOrderOptions;
@@ -10,6 +10,7 @@ const openPerpMarketOrder_1 = require("../openPerpMarketOrder");
10
10
  const positionMaxLeverage_1 = require("../positionMaxLeverage");
11
11
  const auction_1 = require("../auction");
12
12
  const isolatedPositionDeposit_1 = require("../isolatedPositionDeposit");
13
+ // TODO: add isolated margin?
13
14
  /**
14
15
  * Creates a transaction instruction to open multiple non-market orders.
15
16
  */
@@ -34,7 +35,7 @@ exports.createMultipleOpenPerpNonMarketOrderIx = createMultipleOpenPerpNonMarket
34
35
  */
35
36
  const createOpenPerpNonMarketOrderIxs = async (params) => {
36
37
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
37
- const { driftClient, user, marketIndex, direction, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, userOrderId = 0, positionMaxLeverage, isolatedPositionDeposit, additionalIsolatedPositionDeposits, mainSignerOverride, highLeverageOptions, } = params;
38
+ const { driftClient, user, marketIndex, direction, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, userOrderId = 0, positionMaxLeverage, marginMode, mainSignerOverride, highLeverageOptions, isolatedPositionDepositsOverride, } = params;
38
39
  // Support both new (amount + assetType) and legacy (baseAssetAmount) approaches
39
40
  const finalBaseAssetAmount = (0, orderParams_1.resolveBaseAssetAmount)({
40
41
  amount: 'amount' in params ? params.amount : undefined,
@@ -47,23 +48,37 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
47
48
  if (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {
48
49
  throw new Error('Final base asset amount must be greater than zero');
49
50
  }
51
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(isolatedPositionDepositsOverride, {
52
+ driftClient,
53
+ user,
54
+ marketIndex,
55
+ baseAssetAmount: finalBaseAssetAmount,
56
+ direction,
57
+ positionMaxLeverage,
58
+ marginMode,
59
+ replenishUnderwaterPositions: true,
60
+ numOfOpenHighLeverageSpots: highLeverageOptions === null || highLeverageOptions === void 0 ? void 0 : highLeverageOptions.numOfOpenHighLeverageSpots,
61
+ });
62
+ const mainIsolatedPositionDeposit = resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit;
63
+ const resolvedAdditionalDeposits = resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.additionalIsolatedPositionDeposits;
50
64
  const allOrders = [];
51
65
  const allIxs = [];
52
- const leverageIx = await (0, positionMaxLeverage_1.getPositionMaxLeverageIxIfNeeded)(driftClient, user, marketIndex, positionMaxLeverage, mainSignerOverride);
66
+ // Fetch all deposit/leverage ixs in parallel
67
+ const [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] = await Promise.all([
68
+ (0, positionMaxLeverage_1.getPositionMaxLeverageIxIfNeeded)(driftClient, user, marketIndex, positionMaxLeverage, mainSignerOverride),
69
+ (resolvedAdditionalDeposits === null || resolvedAdditionalDeposits === void 0 ? void 0 : resolvedAdditionalDeposits.length)
70
+ ? Promise.all(resolvedAdditionalDeposits.map((deposit) => (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, deposit.marketIndex, deposit.amount, mainSignerOverride)))
71
+ : Promise.resolve([]),
72
+ (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, mainIsolatedPositionDeposit, mainSignerOverride),
73
+ ]);
53
74
  if (leverageIx) {
54
75
  allIxs.push(leverageIx);
55
76
  }
56
- // Add additional isolated position deposit ixs for other under-collateralized positions
57
- if (additionalIsolatedPositionDeposits === null || additionalIsolatedPositionDeposits === void 0 ? void 0 : additionalIsolatedPositionDeposits.length) {
58
- const additionalDepositIxPromises = additionalIsolatedPositionDeposits.map((deposit) => (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, deposit.marketIndex, deposit.amount, mainSignerOverride));
59
- const additionalDepositIxs = await Promise.all(additionalDepositIxPromises);
60
- for (const ix of additionalDepositIxs) {
61
- if (ix) {
62
- allIxs.push(ix);
63
- }
77
+ for (const ix of additionalDepositIxs) {
78
+ if (ix) {
79
+ allIxs.push(ix);
64
80
  }
65
81
  }
66
- const isolatedPositionDepositIx = await (0, isolatedPositionDeposit_1.getIsolatedPositionDepositIxIfNeeded)(driftClient, user, marketIndex, isolatedPositionDeposit, mainSignerOverride);
67
82
  if (isolatedPositionDepositIx) {
68
83
  allIxs.push(isolatedPositionDepositIx);
69
84
  }
@@ -126,7 +141,6 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
126
141
  reduceOnly,
127
142
  postOnly,
128
143
  userOrderId,
129
- positionMaxLeverage,
130
144
  });
131
145
  const bitFlags = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
132
146
  orderParams.bitFlags = bitFlags;
@@ -147,7 +161,6 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
147
161
  limitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,
148
162
  },
149
163
  reduceOnly: (_f = orderConfig.bracketOrders.takeProfit.reduceOnly) !== null && _f !== void 0 ? _f : true,
150
- positionMaxLeverage,
151
164
  });
152
165
  allOrders.push(takeProfitParams);
153
166
  }
@@ -163,7 +176,6 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
163
176
  limitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,
164
177
  },
165
178
  reduceOnly: (_j = orderConfig.bracketOrders.stopLoss.reduceOnly) !== null && _j !== void 0 ? _j : true,
166
- positionMaxLeverage,
167
179
  });
168
180
  allOrders.push(stopLossParams);
169
181
  }
@@ -209,15 +221,25 @@ async function prepSwiftLimitOrderData(params) {
209
221
  reduceOnly: params.reduceOnly,
210
222
  postOnly: params.postOnly,
211
223
  userOrderId: params.userOrderId,
212
- positionMaxLeverage: params.positionMaxLeverage,
213
224
  });
214
225
  const userAccount = user.getUserAccount();
215
226
  return { userAccount, orderParams };
216
227
  }
217
228
  const createSwiftLimitOrder = async (params) => {
218
- var _a, _b;
229
+ var _a, _b, _c;
219
230
  const { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;
220
231
  const { userAccount, orderParams } = await prepSwiftLimitOrderData(params);
232
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(params.isolatedPositionDepositsOverride, {
233
+ driftClient,
234
+ user,
235
+ marketIndex,
236
+ baseAssetAmount: orderParams.baseAssetAmount,
237
+ direction: orderParams.direction,
238
+ positionMaxLeverage: params.positionMaxLeverage,
239
+ marginMode: params.marginMode,
240
+ replenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions
241
+ numOfOpenHighLeverageSpots: (_a = params.highLeverageOptions) === null || _a === void 0 ? void 0 : _a.numOfOpenHighLeverageSpots,
242
+ });
221
243
  await (0, openSwiftOrder_1.prepSignAndSendSwiftOrder)({
222
244
  driftClient,
223
245
  subAccountId: userAccount.subAccountId,
@@ -227,10 +249,10 @@ const createSwiftLimitOrder = async (params) => {
227
249
  swiftOptions,
228
250
  orderParams: {
229
251
  main: orderParams,
230
- takeProfit: (_a = orderConfig.bracketOrders) === null || _a === void 0 ? void 0 : _a.takeProfit,
231
- stopLoss: (_b = orderConfig.bracketOrders) === null || _b === void 0 ? void 0 : _b.stopLoss,
252
+ takeProfit: (_b = orderConfig.bracketOrders) === null || _b === void 0 ? void 0 : _b.takeProfit,
253
+ stopLoss: (_c = orderConfig.bracketOrders) === null || _c === void 0 ? void 0 : _c.stopLoss,
232
254
  positionMaxLeverage: params.positionMaxLeverage,
233
- isolatedPositionDeposit: params.isolatedPositionDeposit,
255
+ isolatedPositionDeposit: resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit,
234
256
  },
235
257
  builderParams: params.builderParams,
236
258
  });
@@ -242,9 +264,20 @@ exports.createSwiftLimitOrder = createSwiftLimitOrder;
242
264
  * @returns The prepared SwiftOrderMessage ready for client-side signing and sending
243
265
  */
244
266
  const createSwiftLimitOrderMessage = async (params) => {
245
- var _a, _b;
267
+ var _a, _b, _c;
246
268
  const { driftClient, user, marketIndex, orderConfig, isDelegate = false, userSigningSlotBuffer, } = params;
247
269
  const { userAccount, orderParams } = await prepSwiftLimitOrderData(params);
270
+ const resolvedDeposits = (0, isolatedPositionDeposit_1.resolveIsolatedPositionDepositsWithOverride)(params.isolatedPositionDepositsOverride, {
271
+ driftClient,
272
+ user,
273
+ marketIndex,
274
+ baseAssetAmount: orderParams.baseAssetAmount,
275
+ direction: orderParams.direction,
276
+ positionMaxLeverage: params.positionMaxLeverage,
277
+ marginMode: params.marginMode,
278
+ replenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions
279
+ numOfOpenHighLeverageSpots: (_a = params.highLeverageOptions) === null || _a === void 0 ? void 0 : _a.numOfOpenHighLeverageSpots,
280
+ });
248
281
  return (0, openSwiftOrder_1.prepSwiftOrderMessage)({
249
282
  driftClient,
250
283
  subAccountId: userAccount.subAccountId,
@@ -254,10 +287,10 @@ const createSwiftLimitOrderMessage = async (params) => {
254
287
  isDelegate,
255
288
  orderParams: {
256
289
  main: orderParams,
257
- takeProfit: (_a = orderConfig.bracketOrders) === null || _a === void 0 ? void 0 : _a.takeProfit,
258
- stopLoss: (_b = orderConfig.bracketOrders) === null || _b === void 0 ? void 0 : _b.stopLoss,
290
+ takeProfit: (_b = orderConfig.bracketOrders) === null || _b === void 0 ? void 0 : _b.takeProfit,
291
+ stopLoss: (_c = orderConfig.bracketOrders) === null || _c === void 0 ? void 0 : _c.stopLoss,
259
292
  positionMaxLeverage: params.positionMaxLeverage,
260
- isolatedPositionDeposit: params.isolatedPositionDeposit,
293
+ isolatedPositionDeposit: resolvedDeposits === null || resolvedDeposits === void 0 ? void 0 : resolvedDeposits.mainDeposit,
261
294
  },
262
295
  builderParams: params.builderParams,
263
296
  });