@drift-labs/common 1.0.16 → 1.0.17

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 (72) hide show
  1. package/lib/clients/DlobWebsocketClient.d.ts +6 -0
  2. package/lib/clients/DlobWebsocketClient.js +24 -4
  3. package/lib/clients/DlobWebsocketClient.js.map +1 -1
  4. package/lib/clients/candleClient.js +12 -0
  5. package/lib/clients/candleClient.js.map +1 -1
  6. package/lib/clients/redisClient.d.ts +1 -0
  7. package/lib/clients/swiftClient.d.ts +1 -0
  8. package/lib/clients/swiftClient.js +19 -5
  9. package/lib/clients/swiftClient.js.map +1 -1
  10. package/lib/clients/tvFeed.d.ts +4 -1
  11. package/lib/clients/tvFeed.js +29 -3
  12. package/lib/clients/tvFeed.js.map +1 -1
  13. package/lib/common-ui-utils/commonUiUtils.d.ts +2 -2
  14. package/lib/common-ui-utils/commonUiUtils.js +38 -3
  15. package/lib/common-ui-utils/commonUiUtils.js.map +1 -1
  16. package/lib/common-ui-utils/order.d.ts +1 -2
  17. package/lib/common-ui-utils/order.js +9 -10
  18. package/lib/common-ui-utils/order.js.map +1 -1
  19. package/lib/common-ui-utils/user.js +23 -20
  20. package/lib/common-ui-utils/user.js.map +1 -1
  21. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +6 -0
  22. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  23. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +1 -0
  24. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
  25. package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +17 -1
  26. package/lib/drift/Drift/clients/CentralServerDrift/index.js +50 -15
  27. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  28. package/lib/drift/base/actions/perp/settlePnl.d.ts +4 -3
  29. package/lib/drift/base/actions/perp/settlePnl.js +6 -3
  30. package/lib/drift/base/actions/perp/settlePnl.js.map +1 -1
  31. package/lib/drift/base/actions/spot/deposit.d.ts +10 -3
  32. package/lib/drift/base/actions/spot/deposit.js +22 -7
  33. package/lib/drift/base/actions/spot/deposit.js.map +1 -1
  34. package/lib/drift/base/actions/trade/editOrder.d.ts +2 -0
  35. package/lib/drift/base/actions/trade/editOrder.js +1 -0
  36. package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
  37. package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +4 -1
  38. package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -4
  39. package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
  40. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +6 -4
  41. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +6 -5
  42. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
  43. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +10 -5
  44. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +18 -15
  45. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  46. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +1 -4
  47. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +9 -10
  48. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  49. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +40 -11
  50. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +49 -15
  51. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  52. package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +5 -3
  53. package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
  54. package/lib/drift/base/actions/user/create.d.ts +3 -1
  55. package/lib/drift/base/actions/user/create.js +21 -7
  56. package/lib/drift/base/actions/user/create.js.map +1 -1
  57. package/lib/drift/cli.js +16 -2
  58. package/lib/drift/cli.js.map +1 -1
  59. package/lib/drift/utils/auctionParamsResponseMapper.d.ts +2 -1
  60. package/lib/drift/utils/auctionParamsResponseMapper.js +1 -1
  61. package/lib/drift/utils/auctionParamsResponseMapper.js.map +1 -1
  62. package/lib/drift/utils/orderParams.js +1 -1
  63. package/lib/drift/utils/orderParams.js.map +1 -1
  64. package/lib/utils/driftEvents.js +18 -2
  65. package/lib/utils/driftEvents.js.map +1 -1
  66. package/lib/utils/index.d.ts +1 -0
  67. package/lib/utils/logger.js +34 -3
  68. package/lib/utils/logger.js.map +1 -1
  69. package/lib/utils/signedMsgs.d.ts +1 -1
  70. package/lib/utils/signedMsgs.js +2 -2
  71. package/lib/utils/signedMsgs.js.map +1 -1
  72. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"order.js","sourceRoot":"","sources":["../../src/common-ui-utils/order.ts"],"names":[],"mappings":";;;AAAA,yCAcyB;AACzB,gDAU6B;AAE7B,oCAAiD;AAEjD,8CAA0D;AAC1D,qCAAwC;AAExC,MAAM,6BAA6B,GAAG,CACrC,YAOC,EACA,EAAE;;IACH,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,MAAM,CAAC;QACtD,OAAO,uBAAc,CAAC,MAAM,CAAC,KAAK,CAAC;IAEpC,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,KAAK,CAAC;QACrD,OAAO,GACN,YAAY,CAAC,iBAAiB;YAC9B,CAAC,CAAA,MAAA,YAAY,CAAC,iBAAiB,0CAAE,MAAM,EAAE,CAAA;YACxC,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,EACJ,GAAG,uBAAc,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IAEjC,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,e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\tBN,\n\tPERCENTAGE_PRECISION,\n\tisOneOfVariant,\n\tMarketType,\n\tDriftClient,\n\tUser,\n\tOrderParamsBitFlag,\n} from '@drift-labs/sdk';\nimport {\n\tLIMIT_ORDER_TYPE_CONFIG,\n\tMARKET_ORDER_TYPE_CONFIG,\n\tORACLE_LIMIT_ORDER_TYPE_CONFIG,\n\tORACLE_MARKET_ORDER_TYPE_CONFIG,\n\tSTOP_LIMIT_ORDER_TYPE_CONFIG,\n\tSTOP_MARKET_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG,\n\tUI_ORDER_TYPES,\n} from '../constants/orders';\nimport { UISerializableOrder } from '../serializableTypes';\nimport { ENUM_UTILS, matchEnum } from '../utils';\nimport { AuctionParams } from '../types';\nimport { EMPTY_AUCTION_PARAMS } from '../constants/trade';\nimport { MARKET_UTILS } from './market';\n\nconst getOrderLabelFromOrderDetails = (\n\torderDetails: Pick<\n\t\tUISerializableOrder,\n\t\t| 'orderType'\n\t\t| 'oraclePriceOffset'\n\t\t| 'direction'\n\t\t| 'triggerCondition'\n\t\t| 'existingPositionDirection'\n\t>\n) => {\n\tif (matchEnum(orderDetails.orderType, OrderType.MARKET))\n\t\treturn UI_ORDER_TYPES.market.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.LIMIT))\n\t\treturn `${\n\t\t\torderDetails.oraclePriceOffset &&\n\t\t\t!orderDetails.oraclePriceOffset?.eqZero()\n\t\t\t\t? 'Oracle '\n\t\t\t\t: ''\n\t\t}${UI_ORDER_TYPES.limit.label}`;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.ORACLE))\n\t\treturn UI_ORDER_TYPES.oracle.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_MARKET)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\t\tif (isTriggered) {\n\t\t\treturn 'Market (Triggered)';\n\t\t}\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isExistingPositionShort = matchEnum(\n\t\t\torderDetails.existingPositionDirection,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\t\tconst isOrderDirectionShort = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isExistingPositionShort\n\t\t\t\t? isOrderDirectionShort\n\t\t\t\t\t? 'Trigger Market' // trigger above, existing position short, order direction short\n\t\t\t\t\t: UI_ORDER_TYPES.stopMarket.label // trigger above, existing position short, order direction long\n\t\t\t\t: isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.takeProfitMarket.label // trigger above, existing position long, order direction short\n\t\t\t\t: 'Trigger Market'; // trigger above, existing position long, order direction long\n\t\t} else {\n\t\t\treturn isExistingPositionShort\n\t\t\t\t? isOrderDirectionShort\n\t\t\t\t\t? 'Trigger Market' // trigger below, existing position short, order direction short\n\t\t\t\t\t: UI_ORDER_TYPES.takeProfitMarket.label // trigger below, existing position short, order direction long\n\t\t\t\t: isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.stopMarket.label // trigger below, existing position long, order direction short\n\t\t\t\t: 'Trigger Market'; // trigger below, existing position long, order direction long\n\t\t}\n\t}\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isExistingPositionLong = matchEnum(\n\t\t\torderDetails.existingPositionDirection,\n\t\t\tPositionDirection.LONG\n\t\t);\n\t\tconst isOrderDirectionLong = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.LONG\n\t\t);\n\n\t\tif (isTriggered) {\n\t\t\treturn 'Limit (Triggered)';\n\t\t}\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isExistingPositionLong\n\t\t\t\t? isOrderDirectionLong\n\t\t\t\t\t? 'Trigger Limit' // trigger above, existing position long, order direction long\n\t\t\t\t\t: UI_ORDER_TYPES.takeProfitLimit.label // trigger above, existing position long, order direction short\n\t\t\t\t: isExistingPositionLong\n\t\t\t\t? UI_ORDER_TYPES.stopLimit.label // trigger above, existing position short, order direction long\n\t\t\t\t: 'Trigger Limit'; // trigger above, existing position short, order direction short\n\t\t} else {\n\t\t\treturn isExistingPositionLong\n\t\t\t\t? isOrderDirectionLong\n\t\t\t\t\t? 'Trigger Limit' // trigger below, existing position long, order direction long\n\t\t\t\t\t: UI_ORDER_TYPES.stopLimit.label // trigger below, existing position long, order direction short\n\t\t\t\t: isExistingPositionLong\n\t\t\t\t? UI_ORDER_TYPES.takeProfitLimit.label // trigger below, existing position short, order direction long\n\t\t\t\t: 'Trigger Limit'; // trigger below, existing position short, order direction short\n\t\t}\n\t}\n\n\treturn '-';\n};\n\nconst getLimitPriceFromOracleOffset = (\n\torder: UISerializableOrder,\n\toraclePrice: BigNum\n): BigNum => {\n\tif (\n\t\t(order.price && !order.price.eqZero()) ||\n\t\t!order.oraclePriceOffset ||\n\t\torder.oraclePriceOffset.eqZero() ||\n\t\t!oraclePrice ||\n\t\toraclePrice?.eqZero()\n\t) {\n\t\treturn order.price;\n\t}\n\treturn oraclePrice.add(order.oraclePriceOffset);\n};\n\nfunction isAuctionEmpty(auctionParams: AuctionParams) {\n\treturn (\n\t\tauctionParams.auctionStartPrice ===\n\t\t\tEMPTY_AUCTION_PARAMS.auctionStartPrice &&\n\t\tauctionParams.auctionEndPrice === EMPTY_AUCTION_PARAMS.auctionEndPrice &&\n\t\tauctionParams.auctionDuration === EMPTY_AUCTION_PARAMS.auctionDuration\n\t);\n}\n\nconst getUIOrderTypeFromSdkOrderType = (\n\torderType: OrderType,\n\ttriggerCondition: OrderTriggerCondition,\n\tdirection: PositionDirection,\n\toracleOffset: BigNum | undefined\n) => {\n\tconst isLong = ENUM_UTILS.match(direction, PositionDirection.LONG);\n\tconst triggerAbove =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.ABOVE) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_ABOVE);\n\n\tconst triggerBelow =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.BELOW) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_BELOW);\n\n\t// Buy side + trigger below: take profit for a short position\n\t// Buy side + trigger above: stop loss for a short position\n\t// Sell side + trigger above: take profit for a long position\n\t// Sell side + trigger below: stop loss for a long position\n\n\tif (matchEnum(orderType, OrderType.MARKET)) {\n\t\treturn MARKET_ORDER_TYPE_CONFIG;\n\t} else if (matchEnum(orderType, OrderType.LIMIT)) {\n\t\tif (oracleOffset && !oracleOffset.eq(ZERO)) {\n\t\t\treturn ORACLE_LIMIT_ORDER_TYPE_CONFIG;\n\t\t} else {\n\t\t\treturn LIMIT_ORDER_TYPE_CONFIG;\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_MARKET)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.ORACLE)) {\n\t\treturn ORACLE_MARKET_ORDER_TYPE_CONFIG;\n\t}\n\tthrow new Error('Invalid order type');\n};\n\nfunction getPerpAuctionDuration(\n\tpriceDiff: BN,\n\tprice: BN,\n\tcontractTier: ContractTier\n): number {\n\tconst percentDiff = priceDiff.mul(PERCENTAGE_PRECISION).div(price);\n\n\tconst slotsPerBp = isOneOfVariant(contractTier, ['a', 'b'])\n\t\t? new BN(100)\n\t\t: new BN(60);\n\n\tconst rawSlots = percentDiff\n\t\t.mul(slotsPerBp)\n\t\t.div(PERCENTAGE_PRECISION.divn(100));\n\n\tconst clamped = BN.min(BN.max(rawSlots, new BN(5)), new BN(180));\n\n\treturn clamped.toNumber();\n}\n\nexport type HighLeverageOptions = {\n\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\tenterHighLeverageModeBufferPct?: number;\n};\n\n/**\n * Mainly checks if the user will be entering high leverage mode through this order.\n */\nfunction getPerpOrderParamsBitFlags(\n\tmarketIndex: number,\n\tdriftClient: DriftClient,\n\tuserAccount: User,\n\tquoteSize: BN,\n\tside: PositionDirection,\n\thighLeverageOptions?: {\n\t\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\t\tenterHighLeverageModeBufferPct?: number;\n\t}\n): number | undefined {\n\tconst {\n\t\tnumOfOpenHighLeverageSpots = Number.MAX_SAFE_INTEGER,\n\t\tenterHighLeverageModeBufferPct = 2,\n\t} = highLeverageOptions || {};\n\n\tif (quoteSize.lte(ZERO) || numOfOpenHighLeverageSpots <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst { hasHighLeverage: isMarketAHighLeverageMarket } =\n\t\tMARKET_UTILS.getMaxLeverageForMarket(\n\t\t\tMarketType.PERP,\n\t\t\tmarketIndex,\n\t\t\tdriftClient\n\t\t);\n\n\tif (!isMarketAHighLeverageMarket) {\n\t\treturn undefined;\n\t}\n\n\t// Check if user is already in high leverage mode\n\tif (userAccount.isHighLeverageMode('Initial')) {\n\t\treturn undefined;\n\t}\n\n\t// Get max trade size without entering high leverage mode\n\tconst maxTradeWithoutHLM = userAccount.getMaxTradeSizeUSDCForPerp(\n\t\tmarketIndex,\n\t\tside,\n\t\tundefined,\n\t\tfalse // enterHighLeverageMode = false\n\t);\n\n\t// If order exceeds non-HLM free collateral, enable high leverage mode\n\t// if within 2%, also enable high lev mode to avoid failures\n\tif (\n\t\tquoteSize.gte(\n\t\t\tmaxTradeWithoutHLM.tradeSize.muln(\n\t\t\t\t1 - enterHighLeverageModeBufferPct / 100\n\t\t\t)\n\t\t)\n\t) {\n\t\treturn OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\treturn undefined;\n}\n\nexport const ORDER_COMMON_UTILS = {\n\tgetOrderLabelFromOrderDetails,\n\tgetLimitPriceFromOracleOffset,\n\tisAuctionEmpty,\n\tgetUIOrderTypeFromSdkOrderType,\n\tgetPerpAuctionDuration,\n\tgetPerpOrderParamsBitFlags,\n};\n"]}
1
+ {"version":3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C;IAED,iDAAiD;IACjD,IAAI,WAAW,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,CAAC;QAC/C,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,IAAI,iBAAiB,GAAG,kBAAkB,EAAE,CAAC;QAC5C,OAAO,wBAAkB,CAAC,sBAAsB,CAAC;IAClD,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAEY,QAAA,kBAAkB,GAAG;IACjC,6BAA6B;IAC7B,6BAA6B;IAC7B,cAAc;IACd,8BAA8B;IAC9B,sBAAsB;IACtB,0BAA0B;CAC1B,CAAC","sourcesContent":["import {\n\tOrderType,\n\tOrderTriggerCondition,\n\tPositionDirection,\n\tBigNum,\n\tZERO,\n\tContractTier,\n\tBN,\n\tPERCENTAGE_PRECISION,\n\tisOneOfVariant,\n\tMarketType,\n\tDriftClient,\n\tUser,\n\tOrderParamsBitFlag,\n} from '@drift-labs/sdk';\nimport {\n\tLIMIT_ORDER_TYPE_CONFIG,\n\tMARKET_ORDER_TYPE_CONFIG,\n\tORACLE_LIMIT_ORDER_TYPE_CONFIG,\n\tORACLE_MARKET_ORDER_TYPE_CONFIG,\n\tSTOP_LIMIT_ORDER_TYPE_CONFIG,\n\tSTOP_MARKET_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG,\n\tUI_ORDER_TYPES,\n} from '../constants/orders';\nimport { UISerializableOrder } from '../serializableTypes';\nimport { ENUM_UTILS, matchEnum } from '../utils';\nimport { AuctionParams } from '../types';\nimport { EMPTY_AUCTION_PARAMS } from '../constants/trade';\nimport { MARKET_UTILS } from './market';\n\nconst getOrderLabelFromOrderDetails = (\n\torderDetails: Pick<\n\t\tUISerializableOrder,\n\t\t| 'orderType'\n\t\t| 'oraclePriceOffset'\n\t\t| 'direction'\n\t\t| 'triggerCondition'\n\t\t| 'existingPositionDirection'\n\t>\n) => {\n\tif (matchEnum(orderDetails.orderType, OrderType.MARKET))\n\t\treturn UI_ORDER_TYPES.market.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.LIMIT))\n\t\treturn `${\n\t\t\torderDetails.oraclePriceOffset &&\n\t\t\t!orderDetails.oraclePriceOffset?.eqZero()\n\t\t\t\t? 'Oracle '\n\t\t\t\t: ''\n\t\t}${UI_ORDER_TYPES.limit.label}`;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.ORACLE))\n\t\treturn UI_ORDER_TYPES.oracle.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_MARKET)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\t\tif (isTriggered) {\n\t\t\treturn 'Market (Triggered)';\n\t\t}\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isExistingPositionShort = matchEnum(\n\t\t\torderDetails.existingPositionDirection,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\t\tconst isOrderDirectionShort = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isExistingPositionShort\n\t\t\t\t? isOrderDirectionShort\n\t\t\t\t\t? 'Trigger Market' // trigger above, existing position short, order direction short\n\t\t\t\t\t: UI_ORDER_TYPES.stopMarket.label // trigger above, existing position short, order direction long\n\t\t\t\t: isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.takeProfitMarket.label // trigger above, existing position long, order direction short\n\t\t\t\t: 'Trigger Market'; // trigger above, existing position long, order direction long\n\t\t} else {\n\t\t\treturn isExistingPositionShort\n\t\t\t\t? isOrderDirectionShort\n\t\t\t\t\t? 'Trigger Market' // trigger below, existing position short, order direction short\n\t\t\t\t\t: UI_ORDER_TYPES.takeProfitMarket.label // trigger below, existing position short, order direction long\n\t\t\t\t: isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.stopMarket.label // trigger below, existing position long, order direction short\n\t\t\t\t: 'Trigger Market'; // trigger below, existing position long, order direction long\n\t\t}\n\t}\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isExistingPositionLong = matchEnum(\n\t\t\torderDetails.existingPositionDirection,\n\t\t\tPositionDirection.LONG\n\t\t);\n\t\tconst isOrderDirectionLong = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.LONG\n\t\t);\n\n\t\tif (isTriggered) {\n\t\t\treturn 'Limit (Triggered)';\n\t\t}\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isExistingPositionLong\n\t\t\t\t? isOrderDirectionLong\n\t\t\t\t\t? 'Trigger Limit' // trigger above, existing position long, order direction long\n\t\t\t\t\t: UI_ORDER_TYPES.takeProfitLimit.label // trigger above, existing position long, order direction short\n\t\t\t\t: isExistingPositionLong\n\t\t\t\t? UI_ORDER_TYPES.stopLimit.label // trigger above, existing position short, order direction long\n\t\t\t\t: 'Trigger Limit'; // trigger above, existing position short, order direction short\n\t\t} else {\n\t\t\treturn isExistingPositionLong\n\t\t\t\t? isOrderDirectionLong\n\t\t\t\t\t? 'Trigger Limit' // trigger below, existing position long, order direction long\n\t\t\t\t\t: UI_ORDER_TYPES.stopLimit.label // trigger below, existing position long, order direction short\n\t\t\t\t: isExistingPositionLong\n\t\t\t\t? UI_ORDER_TYPES.takeProfitLimit.label // trigger below, existing position short, order direction long\n\t\t\t\t: 'Trigger Limit'; // trigger below, existing position short, order direction short\n\t\t}\n\t}\n\n\treturn '-';\n};\n\nconst getLimitPriceFromOracleOffset = (\n\torder: UISerializableOrder,\n\toraclePrice: BigNum\n): BigNum => {\n\tif (\n\t\t(order.price && !order.price.eqZero()) ||\n\t\t!order.oraclePriceOffset ||\n\t\torder.oraclePriceOffset.eqZero() ||\n\t\t!oraclePrice ||\n\t\toraclePrice?.eqZero()\n\t) {\n\t\treturn order.price;\n\t}\n\treturn oraclePrice.add(order.oraclePriceOffset);\n};\n\nfunction isAuctionEmpty(auctionParams: AuctionParams) {\n\treturn (\n\t\tauctionParams.auctionStartPrice ===\n\t\t\tEMPTY_AUCTION_PARAMS.auctionStartPrice &&\n\t\tauctionParams.auctionEndPrice === EMPTY_AUCTION_PARAMS.auctionEndPrice &&\n\t\tauctionParams.auctionDuration === EMPTY_AUCTION_PARAMS.auctionDuration\n\t);\n}\n\nconst getUIOrderTypeFromSdkOrderType = (\n\torderType: OrderType,\n\ttriggerCondition: OrderTriggerCondition,\n\tdirection: PositionDirection,\n\toracleOffset: BigNum | undefined\n) => {\n\tconst isLong = ENUM_UTILS.match(direction, PositionDirection.LONG);\n\tconst triggerAbove =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.ABOVE) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_ABOVE);\n\n\tconst triggerBelow =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.BELOW) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_BELOW);\n\n\t// Buy side + trigger below: take profit for a short position\n\t// Buy side + trigger above: stop loss for a short position\n\t// Sell side + trigger above: take profit for a long position\n\t// Sell side + trigger below: stop loss for a long position\n\n\tif (matchEnum(orderType, OrderType.MARKET)) {\n\t\treturn MARKET_ORDER_TYPE_CONFIG;\n\t} else if (matchEnum(orderType, OrderType.LIMIT)) {\n\t\tif (oracleOffset && !oracleOffset.eq(ZERO)) {\n\t\t\treturn ORACLE_LIMIT_ORDER_TYPE_CONFIG;\n\t\t} else {\n\t\t\treturn LIMIT_ORDER_TYPE_CONFIG;\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_MARKET)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.ORACLE)) {\n\t\treturn ORACLE_MARKET_ORDER_TYPE_CONFIG;\n\t}\n\tthrow new Error('Invalid order type');\n};\n\nfunction getPerpAuctionDuration(\n\tpriceDiff: BN,\n\tprice: BN,\n\tcontractTier: ContractTier\n): number {\n\tconst percentDiff = priceDiff.mul(PERCENTAGE_PRECISION).div(price);\n\n\tconst slotsPerBp = isOneOfVariant(contractTier, ['a', 'b'])\n\t\t? new BN(100)\n\t\t: new BN(60);\n\n\tconst rawSlots = percentDiff\n\t\t.mul(slotsPerBp)\n\t\t.div(PERCENTAGE_PRECISION.divn(100));\n\n\tconst clamped = BN.min(BN.max(rawSlots, new BN(5)), new BN(180));\n\n\treturn clamped.toNumber();\n}\n\nexport type HighLeverageOptions = {\n\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\tenterHighLeverageModeBufferPct?: number;\n};\n\n/**\n * Mainly checks if the user will be entering high leverage mode through this order.\n */\nfunction getPerpOrderParamsBitFlags(\n\tmarketIndex: number,\n\tdriftClient: DriftClient,\n\tuserAccount: User,\n\tattemptedLeverage: number,\n\thighLeverageOptions?: {\n\t\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\t}\n): number | undefined {\n\tif (attemptedLeverage < 5) {\n\t\t// there is no high leverage mode leverage that is higher than 4\n\t\treturn undefined;\n\t}\n\n\tconst { numOfOpenHighLeverageSpots = Number.MAX_SAFE_INTEGER } =\n\t\thighLeverageOptions || {};\n\n\tif (numOfOpenHighLeverageSpots <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst {\n\t\thasHighLeverage: isMarketAHighLeverageMarket,\n\t\tmaxLeverage: regularMaxLeverage,\n\t} = MARKET_UTILS.getMaxLeverageForMarket(\n\t\tMarketType.PERP,\n\t\tmarketIndex,\n\t\tdriftClient\n\t);\n\n\tif (!isMarketAHighLeverageMarket) {\n\t\treturn undefined;\n\t}\n\n\t// Check if user is already in high leverage mode\n\tif (userAccount.isHighLeverageMode('Initial')) {\n\t\treturn undefined;\n\t}\n\n\tif (attemptedLeverage > regularMaxLeverage) {\n\t\treturn OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\treturn undefined;\n}\n\nexport const ORDER_COMMON_UTILS = {\n\tgetOrderLabelFromOrderDetails,\n\tgetLimitPriceFromOracleOffset,\n\tisAuctionEmpty,\n\tgetUIOrderTypeFromSdkOrderType,\n\tgetPerpAuctionDuration,\n\tgetPerpOrderParamsBitFlags,\n};\n"]}
@@ -124,12 +124,14 @@ const checkIfUserAccountExists = async (driftClient, config) => {
124
124
  * There are a few scenarios for how a market's max leverage is defined:
125
125
  *
126
126
  * 1. When the user does not have a position ("empty" or not) in the market in their `UserAccount` data,
127
- * and creates an order for the market, an "empty" `PerpPosition` will be added to the `UserAccount` data,
127
+ * and creates an order for the market, an "empty" `PerpPosition` will be upsert to the `UserAccount` data,
128
128
  * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up
129
129
  * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be
130
- * "empty" if the user does not have the max 8 perp positions open.
130
+ * "empty" if the user does not have the max 8 perp positions open. The max leverage is then derived from
131
+ * the max margin ratio set in the `PerpPosition` struct.
131
132
  *
132
- * 2. When the user has a position ("empty" or not), the max margin ratio is retrieved from the `PerpPosition` struct.
133
+ * 2. If the user has a position ("empty" or not), but no open orders and is provided with a saved max leverage,
134
+ * the saved max leverage is used.
133
135
  *
134
136
  * 3. When the user does not have a position ("empty" or not), it is expected of the UI to store and persist
135
137
  * the max leverage in the UI client.
@@ -150,27 +152,28 @@ const getUserMaxLeverageForMarket = (user, marketIndex, marketLeverageDetails, u
150
152
  return DEFAULT_MAX_LEVERAGE;
151
153
  }
152
154
  const positionHasMaxMarginRatioSet = !!openOrClosedPosition.maxMarginRatio;
155
+ const isPositionOpen = !openOrClosedPosition.baseAssetAmount.eq(sdk_1.ZERO);
156
+ const hasNoOpenOrders = openOrClosedPosition.openOrders === 0;
153
157
  if (positionHasMaxMarginRatioSet) {
158
+ // Special case: open position with no orders - use UI saved value if available
159
+ if (isPositionOpen && hasNoOpenOrders && uiSavedMaxLeverage) {
160
+ return uiSavedMaxLeverage;
161
+ }
154
162
  return parseFloat(((1 / openOrClosedPosition.maxMarginRatio) * 10000).toFixed(2));
155
163
  }
156
- else {
157
- const isOpenPositionWithoutMaxMarginRatio = !openOrClosedPosition.baseAssetAmount.eq(sdk_1.ZERO);
158
- if (isOpenPositionWithoutMaxMarginRatio) {
159
- // user has an existing position from before PML ship (this means no max margin ratio set onchain)
160
- // display max leverage for the leverage mode their account is in
161
- const isUserInHighLeverageMode = user.isHighLeverageMode('Initial');
162
- const grandfatheredMaxLev = isUserInHighLeverageMode
163
- ? marketLeverageDetails.hasHighLeverage
164
- ? marketLeverageDetails.highLeverageMaxLeverage
165
- : marketLeverageDetails.regularMaxLeverage
166
- : marketLeverageDetails.regularMaxLeverage;
167
- return grandfatheredMaxLev;
168
- }
169
- else {
170
- // user has closed position with no margin ratio set, return default value
171
- return DEFAULT_MAX_LEVERAGE;
172
- }
164
+ if (isPositionOpen) {
165
+ // user has an existing position from before PML ship (this means no max margin ratio set onchain yet)
166
+ // display max leverage for the leverage mode their account is in
167
+ const isUserInHighLeverageMode = user.isHighLeverageMode('Initial');
168
+ const grandfatheredMaxLev = isUserInHighLeverageMode
169
+ ? marketLeverageDetails.hasHighLeverage
170
+ ? marketLeverageDetails.highLeverageMaxLeverage
171
+ : marketLeverageDetails.regularMaxLeverage
172
+ : marketLeverageDetails.regularMaxLeverage;
173
+ return grandfatheredMaxLev;
173
174
  }
175
+ // user has closed position with no margin ratio set, return default value
176
+ return DEFAULT_MAX_LEVERAGE;
174
177
  };
175
178
  exports.USER_UTILS = {
176
179
  getOpenPositionData,
@@ -1 +1 @@
1
- {"version":3,"file":"user.js","sourceRoot":"","sources":["../../src/common-ui-utils/user.ts"],"names":[],"mappings":";;;AAAA,yCA0ByB;AACzB,oCAAkD;AAClD,uCAA0C;AAC1C,oCAAsC;AAEtC,MAAM,mBAAmB,GAAG,CAC3B,WAAwB,EACxB,aAA6B,EAC7B,IAAU,EACV,gBAAoC,EACpC,iBAA+C,EAC9B,EAAE;IACnB,MAAM,gBAAgB,GAAG,WAAW,CAAC,eA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C7B,CAAC;IAED,MAAM,4BAA4B,GAAG,CAAC,CAAC,oBAAoB,CAAC,cAAc,CAAC;IAE3E,IAAI,4BAA4B,EAAE,CAAC;QAClC,OAAO,UAAU,CAChB,CAAC,CAAC,CAAC,GAAG,oBAAoB,CAAC,cAAc,CAAC,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAC9D,CAAC;IACH,CAAC;SAAM,CAAC;QACP,MAAM,mCAAmC,GACxC,CAAC,oBAAoB,CAAC,eAAe,CAAC,EAAE,CAAC,UAAI,CAAC,CAAC;QAEhD,IAAI,mCAAmC,EAAE,CAAC;YACzC,kGAAkG;YAClG,iEAAiE;YACjE,MAAM,wBAAwB,GAAG,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;YACpE,MAAM,mBAAmB,GAAG,wBAAwB;gBACnD,CAAC,CAAC,qBAAqB,CAAC,eAAe;oBACtC,CAAC,CAAC,qBAAqB,CAAC,uBAAuB;oBAC/C,CAAC,CAAC,qBAAqB,CAAC,kBAAkB;gBAC3C,CAAC,CAAC,qBAAqB,CAAC,kBAAkB,CAAC;YAC5C,OAAO,mBAAmB,CAAC;QAC5B,CAAC;aAAM,CAAC;YACP,0EAA0E;YAC1E,OAAO,oBAAoB,CAAC;QAC7B,CAAC;IACF,CAAC;AACF,CAAC,CAAC;AAEW,QAAA,UAAU,GAAG;IACzB,mBAAmB;IACnB,wBAAwB;IACxB,2BAA2B;CAC3B,CAAC","sourcesContent":["import {\n\tBASE_PRECISION_EXP,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMarketStatus,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketConfig,\n\tPerpPosition,\n\tPositionDirection,\n\tPublicKey,\n\tQUOTE_PRECISION_EXP,\n\tQUOTE_SPOT_MARKET_INDEX,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateCostBasis,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tgetUserAccountPublicKeySync,\n\tcalculateUnsettledFundingPnl,\n\tisOracleValid,\n\tAMM_RESERVE_PRECISION,\n} from '@drift-labs/sdk';\nimport { OpenPosition, UIMarket } from '../types';\nimport { TRADING_UTILS } from './trading';\nimport { ENUM_UTILS } from '../utils';\n\nconst getOpenPositionData = (\n\tdriftClient: DriftClient,\n\tuserPositions: PerpPosition[],\n\tuser: User,\n\tperpMarketLookup: PerpMarketConfig[],\n\tmarkPriceCallback?: (marketIndex: number) => BN\n): OpenPosition[] => {\n\tconst oracleGuardRails = driftClient.getStateAccount().oracleGuardRails;\n\n\tconst newResult: OpenPosition[] = userPositions\n\t\t.filter(\n\t\t\t(position) =>\n\t\t\t\t!position.baseAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.quoteAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.lpShares.eq(ZERO)\n\t\t)\n\t\t.map((position) => {\n\t\t\tconst perpMarketConfig = perpMarketLookup[position.marketIndex];\n\t\t\tconst perpMarket = driftClient.getPerpMarketAccount(position.marketIndex);\n\n\t\t\tconst usdcSpotMarket = driftClient.getSpotMarketAccount(\n\t\t\t\tQUOTE_SPOT_MARKET_INDEX\n\t\t\t);\n\n\t\t\tconst oraclePriceData = driftClient.getOracleDataForPerpMarket(\n\t\t\t\tposition.marketIndex\n\t\t\t);\n\n\t\t\tlet oraclePrice = oraclePriceData.price;\n\n\t\t\t// mark price fetched with a callback so we don't need extra dlob server calls. fallback to oracle\n\t\t\tlet markPrice = markPriceCallback\n\t\t\t\t? markPriceCallback(position.marketIndex) ?? oraclePriceData.price\n\t\t\t\t: oraclePriceData.price;\n\n\t\t\tlet estExitPrice = user.getPositionEstimatedExitPriceAndPnl(\n\t\t\t\tposition,\n\t\t\t\tposition.baseAssetAmount\n\t\t\t)[0];\n\n\t\t\tconst entryPrice = calculateEntryPrice(position);\n\n\t\t\tconst isShort = position.baseAssetAmount.isNeg();\n\n\t\t\tif (UIMarket.checkIsPredictionMarket(perpMarketConfig)) {\n\t\t\t\tconst isResolved =\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.SETTLEMENT) ||\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.DELISTED);\n\n\t\t\t\tif (isResolved) {\n\t\t\t\t\tconst resolvedToNo = perpMarket.expiryPrice.lte(\n\t\t\t\t\t\tZERO.add(perpMarket.amm.orderTickSize)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst price = resolvedToNo\n\t\t\t\t\t\t? ZERO.mul(PRICE_PRECISION)\n\t\t\t\t\t\t: ONE.mul(PRICE_PRECISION);\n\n\t\t\t\t\testExitPrice = price;\n\t\t\t\t\tmarkPrice = price;\n\t\t\t\t\toraclePrice = price;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if for any reason oracle or mark price blips to 0, fallback to the other one so we don't show a crazy pnl\n\t\t\tif (markPrice.lte(ZERO) && oraclePrice.gt(ZERO)) {\n\t\t\t\tmarkPrice = oraclePrice;\n\t\t\t}\n\n\t\t\tif (oraclePrice.lte(ZERO) && markPrice.gt(ZERO)) {\n\t\t\t\toraclePrice = markPrice;\n\t\t\t}\n\n\t\t\tconst pnlVsMark = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(markPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\tconst pnlVsOracle = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(oraclePrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\treturn {\n\t\t\t\tmarketIndex: position.marketIndex,\n\t\t\t\tmarketSymbol: perpMarketConfig.symbol,\n\t\t\t\tdirection: isShort ? 'short' : 'long',\n\t\t\t\tnotional: position.baseAssetAmount\n\t\t\t\t\t.abs()\n\t\t\t\t\t.mul(markPrice)\n\t\t\t\t\t.div(AMM_RESERVE_PRECISION),\n\t\t\t\tbaseSize: position.baseAssetAmount,\n\t\t\t\tmarkPrice,\n\t\t\t\tentryPrice,\n\t\t\t\texitPrice: estExitPrice,\n\t\t\t\tliqPrice: user.liquidationPrice(position.marketIndex, ZERO),\n\t\t\t\tquoteAssetNotionalAmount: position.quoteAssetAmount,\n\t\t\t\tquoteEntryAmount: position.quoteEntryAmount,\n\t\t\t\tquoteBreakEvenAmount: position.quoteBreakEvenAmount,\n\t\t\t\tpnlVsMark,\n\t\t\t\tpnlVsOracle,\n\t\t\t\tunsettledPnl: calculateClaimablePnl(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tusdcSpotMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunsettledFundingPnl: calculateUnsettledFundingPnl(perpMarket, position),\n\t\t\t\t// Includes both settled and unsettled funding as well as fees\n\t\t\t\tfeesAndFundingPnl: calculateFeesAndFundingPnl(perpMarket, position),\n\t\t\t\ttotalUnrealizedPnl: calculatePositionPNL(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\ttrue,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunrealizedFundingPnl: user.getUnrealizedFundingPNL(\n\t\t\t\t\tposition.marketIndex\n\t\t\t\t),\n\t\t\t\tlastCumulativeFundingRate: position.lastCumulativeFundingRate,\n\t\t\t\topenOrders: position.openOrders,\n\t\t\t\tcostBasis: calculateCostBasis(position),\n\t\t\t\trealizedPnl: position.settledPnl,\n\t\t\t\tpnlIsClaimable: isOracleValid(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\toraclePriceData,\n\t\t\t\t\toracleGuardRails,\n\t\t\t\t\tperpMarket.amm.lastUpdateSlot?.toNumber()\n\t\t\t\t),\n\t\t\t\tlpShares: position.lpShares,\n\t\t\t\tremainderBaseAmount: position.remainderBaseAssetAmount ?? 0,\n\t\t\t\tlpDeriskPrice: user.liquidationPrice(\n\t\t\t\t\tposition.marketIndex,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t'Initial',\n\t\t\t\t\ttrue\n\t\t\t\t),\n\t\t\t\tmaxMarginRatio: position.maxMarginRatio,\n\t\t\t};\n\t\t});\n\n\treturn newResult;\n};\n\nconst checkIfUserAccountExists = async (\n\tdriftClient: DriftClient,\n\tconfig:\n\t\t| {\n\t\t\t\ttype: 'userPubKey';\n\t\t\t\tuserPubKey: PublicKey;\n\t\t }\n\t\t| {\n\t\t\t\ttype: 'subAccountId';\n\t\t\t\tsubAccountId: number;\n\t\t\t\tauthority: PublicKey;\n\t\t }\n) => {\n\tlet userPubKey: PublicKey;\n\n\tif (config.type === 'userPubKey') {\n\t\tuserPubKey = config.userPubKey;\n\t} else {\n\t\tuserPubKey = getUserAccountPublicKeySync(\n\t\t\tdriftClient.program.programId,\n\t\t\tconfig.authority,\n\t\t\tconfig.subAccountId\n\t\t);\n\t}\n\n\tconst accountInfo = await driftClient.connection.getAccountInfo(userPubKey);\n\n\treturn accountInfo !== null;\n};\n\n/**\n * A user's max leverage for a market is stored on-chain in the `PerpPosition` struct of the `UserAccount`.\n * There are a few scenarios for how a market's max leverage is defined:\n *\n * 1. When the user does not have a position (\"empty\" or not) in the market in their `UserAccount` data,\n * and creates an order for the market, an \"empty\" `PerpPosition` will be added to the `UserAccount` data,\n * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up\n * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be\n * \"empty\" if the user does not have the max 8 perp positions open.\n *\n * 2. When the user has a position (\"empty\" or not), the max margin ratio is retrieved from the `PerpPosition` struct.\n *\n * 3. When the user does not have a position (\"empty\" or not), it is expected of the UI to store and persist\n * the max leverage in the UI client.\n *\n * 4. In cases where the user has a position before the market max leverage feature was shipped, the\n * position is not expected to have a max margin ratio set, and the UI should display the regular max\n * leverage for the market, unless the user is already in High Leverage Mode, in which case the UI should\n * display the high leverage max leverage for the market (if any).\n */\nconst getUserMaxLeverageForMarket = (\n\tuser: User | undefined,\n\tmarketIndex: number,\n\tmarketLeverageDetails: {\n\t\tregularMaxLeverage: number;\n\t\thighLeverageMaxLeverage: number;\n\t\thasHighLeverage: boolean;\n\t},\n\tuiSavedMaxLeverage?: number\n) => {\n\t// if no saved max leverage is provided, return the regular max leverage for the market\n\tconst DEFAULT_MAX_LEVERAGE =\n\t\tuiSavedMaxLeverage ?? marketLeverageDetails.regularMaxLeverage;\n\n\tif (!user) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst openOrClosedPosition = user.getPerpPosition(marketIndex); // this position does not have to be open, it can be a closed position (a.k.a \"empty\") but has max margin ratio set.\n\n\tif (!openOrClosedPosition) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst positionHasMaxMarginRatioSet = !!openOrClosedPosition.maxMarginRatio;\n\n\tif (positionHasMaxMarginRatioSet) {\n\t\treturn parseFloat(\n\t\t\t((1 / openOrClosedPosition.maxMarginRatio) * 10000).toFixed(2)\n\t\t);\n\t} else {\n\t\tconst isOpenPositionWithoutMaxMarginRatio =\n\t\t\t!openOrClosedPosition.baseAssetAmount.eq(ZERO);\n\n\t\tif (isOpenPositionWithoutMaxMarginRatio) {\n\t\t\t// user has an existing position from before PML ship (this means no max margin ratio set onchain)\n\t\t\t// display max leverage for the leverage mode their account is in\n\t\t\tconst isUserInHighLeverageMode = user.isHighLeverageMode('Initial');\n\t\t\tconst grandfatheredMaxLev = isUserInHighLeverageMode\n\t\t\t\t? marketLeverageDetails.hasHighLeverage\n\t\t\t\t\t? marketLeverageDetails.highLeverageMaxLeverage\n\t\t\t\t\t: marketLeverageDetails.regularMaxLeverage\n\t\t\t\t: marketLeverageDetails.regularMaxLeverage;\n\t\t\treturn grandfatheredMaxLev;\n\t\t} else {\n\t\t\t// user has closed position with no margin ratio set, return default value\n\t\t\treturn DEFAULT_MAX_LEVERAGE;\n\t\t}\n\t}\n};\n\nexport const USER_UTILS = {\n\tgetOpenPositionData,\n\tcheckIfUserAccountExists,\n\tgetUserMaxLeverageForMarket,\n};\n"]}
1
+ {"version":3,"file":"user.js","sourceRoot":"","sources":["../../src/common-ui-utils/user.ts"],"names":[],"mappings":";;;AAAA,yCA0ByB;AACzB,oCAAkD;AAClD,uCAA0C;AAC1C,oCAAsC;AAEtC,MAAM,mBAAmB,GAAG,CAC3B,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n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketConfig,\n\tPerpPosition,\n\tPositionDirection,\n\tPublicKey,\n\tQUOTE_PRECISION_EXP,\n\tQUOTE_SPOT_MARKET_INDEX,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateCostBasis,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tgetUserAccountPublicKeySync,\n\tcalculateUnsettledFundingPnl,\n\tisOracleValid,\n\tAMM_RESERVE_PRECISION,\n} from '@drift-labs/sdk';\nimport { OpenPosition, UIMarket } from '../types';\nimport { TRADING_UTILS } from './trading';\nimport { ENUM_UTILS } from '../utils';\n\nconst getOpenPositionData = (\n\tdriftClient: DriftClient,\n\tuserPositions: PerpPosition[],\n\tuser: User,\n\tperpMarketLookup: PerpMarketConfig[],\n\tmarkPriceCallback?: (marketIndex: number) => BN\n): OpenPosition[] => {\n\tconst oracleGuardRails = driftClient.getStateAccount().oracleGuardRails;\n\n\tconst newResult: OpenPosition[] = userPositions\n\t\t.filter(\n\t\t\t(position) =>\n\t\t\t\t!position.baseAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.quoteAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.lpShares.eq(ZERO)\n\t\t)\n\t\t.map((position) => {\n\t\t\tconst perpMarketConfig = perpMarketLookup[position.marketIndex];\n\t\t\tconst perpMarket = driftClient.getPerpMarketAccount(position.marketIndex);\n\n\t\t\tconst usdcSpotMarket = driftClient.getSpotMarketAccount(\n\t\t\t\tQUOTE_SPOT_MARKET_INDEX\n\t\t\t);\n\n\t\t\tconst oraclePriceData = driftClient.getOracleDataForPerpMarket(\n\t\t\t\tposition.marketIndex\n\t\t\t);\n\n\t\t\tlet oraclePrice = oraclePriceData.price;\n\n\t\t\t// mark price fetched with a callback so we don't need extra dlob server calls. fallback to oracle\n\t\t\tlet markPrice = markPriceCallback\n\t\t\t\t? markPriceCallback(position.marketIndex) ?? oraclePriceData.price\n\t\t\t\t: oraclePriceData.price;\n\n\t\t\tlet estExitPrice = user.getPositionEstimatedExitPriceAndPnl(\n\t\t\t\tposition,\n\t\t\t\tposition.baseAssetAmount\n\t\t\t)[0];\n\n\t\t\tconst entryPrice = calculateEntryPrice(position);\n\n\t\t\tconst isShort = position.baseAssetAmount.isNeg();\n\n\t\t\tif (UIMarket.checkIsPredictionMarket(perpMarketConfig)) {\n\t\t\t\tconst isResolved =\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.SETTLEMENT) ||\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.DELISTED);\n\n\t\t\t\tif (isResolved) {\n\t\t\t\t\tconst resolvedToNo = perpMarket.expiryPrice.lte(\n\t\t\t\t\t\tZERO.add(perpMarket.amm.orderTickSize)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst price = resolvedToNo\n\t\t\t\t\t\t? ZERO.mul(PRICE_PRECISION)\n\t\t\t\t\t\t: ONE.mul(PRICE_PRECISION);\n\n\t\t\t\t\testExitPrice = price;\n\t\t\t\t\tmarkPrice = price;\n\t\t\t\t\toraclePrice = price;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if for any reason oracle or mark price blips to 0, fallback to the other one so we don't show a crazy pnl\n\t\t\tif (markPrice.lte(ZERO) && oraclePrice.gt(ZERO)) {\n\t\t\t\tmarkPrice = oraclePrice;\n\t\t\t}\n\n\t\t\tif (oraclePrice.lte(ZERO) && markPrice.gt(ZERO)) {\n\t\t\t\toraclePrice = markPrice;\n\t\t\t}\n\n\t\t\tconst pnlVsMark = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(markPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\tconst pnlVsOracle = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(oraclePrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\treturn {\n\t\t\t\tmarketIndex: position.marketIndex,\n\t\t\t\tmarketSymbol: perpMarketConfig.symbol,\n\t\t\t\tdirection: isShort ? 'short' : 'long',\n\t\t\t\tnotional: position.baseAssetAmount\n\t\t\t\t\t.abs()\n\t\t\t\t\t.mul(markPrice)\n\t\t\t\t\t.div(AMM_RESERVE_PRECISION),\n\t\t\t\tbaseSize: position.baseAssetAmount,\n\t\t\t\tmarkPrice,\n\t\t\t\tentryPrice,\n\t\t\t\texitPrice: estExitPrice,\n\t\t\t\tliqPrice: user.liquidationPrice(position.marketIndex, ZERO),\n\t\t\t\tquoteAssetNotionalAmount: position.quoteAssetAmount,\n\t\t\t\tquoteEntryAmount: position.quoteEntryAmount,\n\t\t\t\tquoteBreakEvenAmount: position.quoteBreakEvenAmount,\n\t\t\t\tpnlVsMark,\n\t\t\t\tpnlVsOracle,\n\t\t\t\tunsettledPnl: calculateClaimablePnl(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tusdcSpotMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunsettledFundingPnl: calculateUnsettledFundingPnl(perpMarket, position),\n\t\t\t\t// Includes both settled and unsettled funding as well as fees\n\t\t\t\tfeesAndFundingPnl: calculateFeesAndFundingPnl(perpMarket, position),\n\t\t\t\ttotalUnrealizedPnl: calculatePositionPNL(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\ttrue,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunrealizedFundingPnl: user.getUnrealizedFundingPNL(\n\t\t\t\t\tposition.marketIndex\n\t\t\t\t),\n\t\t\t\tlastCumulativeFundingRate: position.lastCumulativeFundingRate,\n\t\t\t\topenOrders: position.openOrders,\n\t\t\t\tcostBasis: calculateCostBasis(position),\n\t\t\t\trealizedPnl: position.settledPnl,\n\t\t\t\tpnlIsClaimable: isOracleValid(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\toraclePriceData,\n\t\t\t\t\toracleGuardRails,\n\t\t\t\t\tperpMarket.amm.lastUpdateSlot?.toNumber()\n\t\t\t\t),\n\t\t\t\tlpShares: position.lpShares,\n\t\t\t\tremainderBaseAmount: position.remainderBaseAssetAmount ?? 0,\n\t\t\t\tlpDeriskPrice: user.liquidationPrice(\n\t\t\t\t\tposition.marketIndex,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t'Initial',\n\t\t\t\t\ttrue\n\t\t\t\t),\n\t\t\t\tmaxMarginRatio: position.maxMarginRatio,\n\t\t\t};\n\t\t});\n\n\treturn newResult;\n};\n\nconst checkIfUserAccountExists = async (\n\tdriftClient: DriftClient,\n\tconfig:\n\t\t| {\n\t\t\t\ttype: 'userPubKey';\n\t\t\t\tuserPubKey: PublicKey;\n\t\t }\n\t\t| {\n\t\t\t\ttype: 'subAccountId';\n\t\t\t\tsubAccountId: number;\n\t\t\t\tauthority: PublicKey;\n\t\t }\n) => {\n\tlet userPubKey: PublicKey;\n\n\tif (config.type === 'userPubKey') {\n\t\tuserPubKey = config.userPubKey;\n\t} else {\n\t\tuserPubKey = getUserAccountPublicKeySync(\n\t\t\tdriftClient.program.programId,\n\t\t\tconfig.authority,\n\t\t\tconfig.subAccountId\n\t\t);\n\t}\n\n\tconst accountInfo = await driftClient.connection.getAccountInfo(userPubKey);\n\n\treturn accountInfo !== null;\n};\n\n/**\n * A user's max leverage for a market is stored on-chain in the `PerpPosition` struct of the `UserAccount`.\n * There are a few scenarios for how a market's max leverage is defined:\n *\n * 1. When the user does not have a position (\"empty\" or not) in the market in their `UserAccount` data,\n * and creates an order for the market, an \"empty\" `PerpPosition` will be upsert to the `UserAccount` data,\n * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up\n * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be\n * \"empty\" if the user does not have the max 8 perp positions open. The max leverage is then derived from\n * the max margin ratio set in the `PerpPosition` struct.\n *\n * 2. If the user has a position (\"empty\" or not), but no open orders and is provided with a saved max leverage,\n * the saved max leverage is used.\n *\n * 3. When the user does not have a position (\"empty\" or not), it is expected of the UI to store and persist\n * the max leverage in the UI client.\n *\n * 4. In cases where the user has a position before the market max leverage feature was shipped, the\n * position is not expected to have a max margin ratio set, and the UI should display the regular max\n * leverage for the market, unless the user is already in High Leverage Mode, in which case the UI should\n * display the high leverage max leverage for the market (if any).\n */\nconst getUserMaxLeverageForMarket = (\n\tuser: User | undefined,\n\tmarketIndex: number,\n\tmarketLeverageDetails: {\n\t\tregularMaxLeverage: number;\n\t\thighLeverageMaxLeverage: number;\n\t\thasHighLeverage: boolean;\n\t},\n\tuiSavedMaxLeverage?: number\n) => {\n\t// if no saved max leverage is provided, return the regular max leverage for the market\n\tconst DEFAULT_MAX_LEVERAGE =\n\t\tuiSavedMaxLeverage ?? marketLeverageDetails.regularMaxLeverage;\n\n\tif (!user) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst openOrClosedPosition = user.getPerpPosition(marketIndex); // this position does not have to be open, it can be a closed position (a.k.a \"empty\") but has max margin ratio set.\n\n\tif (!openOrClosedPosition) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst positionHasMaxMarginRatioSet = !!openOrClosedPosition.maxMarginRatio;\n\tconst isPositionOpen = !openOrClosedPosition.baseAssetAmount.eq(ZERO);\n\tconst hasNoOpenOrders = openOrClosedPosition.openOrders === 0;\n\n\tif (positionHasMaxMarginRatioSet) {\n\t\t// Special case: open position with no orders - use UI saved value if available\n\t\tif (isPositionOpen && hasNoOpenOrders && uiSavedMaxLeverage) {\n\t\t\treturn uiSavedMaxLeverage;\n\t\t}\n\n\t\treturn parseFloat(\n\t\t\t((1 / openOrClosedPosition.maxMarginRatio) * 10000).toFixed(2)\n\t\t);\n\t}\n\n\tif (isPositionOpen) {\n\t\t// user has an existing position from before PML ship (this means no max margin ratio set onchain yet)\n\t\t// display max leverage for the leverage mode their account is in\n\t\tconst isUserInHighLeverageMode = user.isHighLeverageMode('Initial');\n\t\tconst grandfatheredMaxLev = isUserInHighLeverageMode\n\t\t\t? marketLeverageDetails.hasHighLeverage\n\t\t\t\t? marketLeverageDetails.highLeverageMaxLeverage\n\t\t\t\t: marketLeverageDetails.regularMaxLeverage\n\t\t\t: marketLeverageDetails.regularMaxLeverage;\n\t\treturn grandfatheredMaxLev;\n\t}\n\n\t// user has closed position with no margin ratio set, return default value\n\treturn DEFAULT_MAX_LEVERAGE;\n};\n\nexport const USER_UTILS = {\n\tgetOpenPositionData,\n\tcheckIfUserAccountExists,\n\tgetUserMaxLeverageForMarket,\n};\n"]}
@@ -325,6 +325,7 @@ class DriftOperations {
325
325
  marketIndex: params.marketIndex,
326
326
  optionalAuctionParamsInputs: params.orderConfig.optionalAuctionParamsInputs,
327
327
  builderParams: params.builderParams,
328
+ positionMaxLeverage: params.positionMaxLeverage,
328
329
  });
329
330
  return swiftOrderResult;
330
331
  }
@@ -340,6 +341,7 @@ class DriftOperations {
340
341
  optionalAuctionParamsInputs: params.orderConfig.optionalAuctionParamsInputs,
341
342
  dlobServerHttpUrl: this.dlobServerHttpUrl,
342
343
  useSwift: false,
344
+ positionMaxLeverage: params.positionMaxLeverage,
343
345
  });
344
346
  const { txSig } = await this.driftClient.sendTransaction(result);
345
347
  return txSig;
@@ -376,6 +378,7 @@ class DriftOperations {
376
378
  ...params.orderConfig.swiftOptions,
377
379
  },
378
380
  builderParams: params.builderParams,
381
+ positionMaxLeverage: params.positionMaxLeverage,
379
382
  });
380
383
  return swiftOrderResult;
381
384
  }
@@ -396,6 +399,7 @@ class DriftOperations {
396
399
  postOnly: params.postOnly,
397
400
  useSwift: false,
398
401
  txParams: this.getTxParams(),
402
+ positionMaxLeverage: params.positionMaxLeverage,
399
403
  });
400
404
  const { txSig } = await this.driftClient.sendTransaction(txn);
401
405
  return txSig;
@@ -418,6 +422,7 @@ class DriftOperations {
418
422
  reduceOnly: params.reduceOnly,
419
423
  useSwift: false,
420
424
  txParams: this.getTxParams(),
425
+ positionMaxLeverage: params.positionMaxLeverage,
421
426
  });
422
427
  const { txSig } = await this.driftClient.sendTransaction(txn);
423
428
  return txSig;
@@ -437,6 +442,7 @@ class DriftOperations {
437
442
  reduceOnly: params.reduceOnly,
438
443
  useSwift: false,
439
444
  txParams: this.getTxParams(),
445
+ positionMaxLeverage: params.positionMaxLeverage,
440
446
  });
441
447
  const { txSig } = await this.driftClient.sendTransaction(txn);
442
448
  return txSig;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/index.ts"],"names":[],"mappings":";;;AAAA,yCAYyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAW7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AACnH,wGAAwG;AAExG;;;;;;;GAOG;AACH,MAAa,eAAe;IAS3B;;;;;;OAMG;IACH,YACS,WAAwB,EACxB,mBAA2C,EAC3C,iBAAyB,EACzB,cAAsB,EACtB,cAA4B;QAJ5B,gBAAW,GAAX,WAAW,CAAa;QACxB,wBAAmB,GAAnB,mBAAmB,CAAwB;QAC3C,sBAAiB,GAAjB,iBAAiB,CAAQ;QACzB,mBAAc,GAAd,cAAc,CAAQ;QACtB,mBAAc,GAAd,cAAc,CAAc;IAClC,CAAC;IAEJ;;;OAGG;IACH,WAAW,CAAC,SAA6B;;QACxC,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CACnC,MAAA,IAAI,CAAC,cAAc,EAAE,mCACpB,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,CACpD,CAAC;QAEF,MAAM,eAAe,GAAG,IAAI,CAAC,GAAG,CAC/B,iBAAiB,EACjB,eAAe,CAAC,uBAAuB,CACvC,CAAC;QAEF,OAAO;YACN,GAAG,eAAe,CAAC,iBAAiB;YACpC,iBAAiB,EAAE,eAAe;YAClC,GAAG,SAAS;SACZ,CAAC;IACH,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,KAAK,CAAC,oBAAoB,CAAC,MAAkC;;QAI5D,MAAM,EACL,aAAa,EACb,sBAAsB,EACtB,c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AC,gBAAgB,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,eAAe,GAAG,MAAM,IAAA,mCAAqB,EAAC;YACnD,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,IAAI,EAAE,WAAW,CAAC,UAAU;YAC5B,QAAQ;YACR,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE;SAC5B,CAAC,CAAC;QAEH,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;QAE1E,OAAO,KAAK,CAAC;IACd,CAAC;;AAnsBF,0CAosBC;AAnsBgB,iCAAiB,GAAa;IAC7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AA+rBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n\tCreateRevenueShareEscrowParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createRevenueShareEscrowTxn } from '../../../../base/actions/builder/createRevenueShareEscrow';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tgetTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tlet userStatsAccount: UserStatsAccount | undefined = undefined;\n\n\t\ttry {\n\t\t\tuserStatsAccount = this.driftClient.userStats?.getAccount();\n\t\t} catch (error) {\n\t\t\t// ignore\n\t\t}\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: userStatsAccount,\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a RevenueShareEscrow account for the user.\n\t *\n\t * @param params - The parameters for creating a RevenueShareEscrow account\n\t * @returns Promise resolving to the transaction signature of the creation\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.createRevenueShareEscrow({\n\t * numOrders: 16,\n\t * builder: {\n\t * builderAuthority: new PublicKey(\"builderAuthority\"),\n\t * maxFeeTenthBps: 100,\n\t * },\n\t * });\n\t * ```\n\t */\n\tasync createRevenueShareEscrow(\n\t\tparams: CreateRevenueShareEscrowParams\n\t): Promise<TransactionSignature> {\n\t\tconst txn = await createRevenueShareEscrowTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\tnumOrders: params.numOrders ?? 16,\n\t\t\tbuilder: params.builder,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserPublicKey: user.userClient.userAccountPublicKey,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\torderIds,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/index.ts"],"names":[],"mappings":";;;AAAA,yCAYyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAW7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AACnH,wGAAwG;AAExG;;;;;;;GAOG;AACH,MAAa,eAAe;IAS3B;;;;;;OAMG;IACH,YACS,WAAwB,EACxB,mBAA2C,EAC3C,iBAAyB,EACzB,cAAsB,EACtB,cAA4B;QAJ5B,gBAAW,GAAX,WAAW,CAAa;QACxB,wBAAmB,GAAnB,mBAAmB,CAAwB;QAC3C,sBAAiB,GAAjB,iBAAiB,CAAQ;QACzB,mBAAc,GAAd,cAAc,CAAQ;QACtB,mBAAc,GAAd,cAAc,CAAc;IAClC,CAAC;IAEJ;;;OAGG;IACH,WAAW,CAAC,SAA6B;;QACxC,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CACnC,MAAA,IAAI,CAAC,cAAc,EAAE,mCACpB,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,CACpD,CAAC;QAEF,MAAM,eAAe,GAAG,I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tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n\tCreateRevenueShareEscrowParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createRevenueShareEscrowTxn } from '../../../../base/actions/builder/createRevenueShareEscrow';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tgetTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tlet userStatsAccount: UserStatsAccount | undefined = undefined;\n\n\t\ttry {\n\t\t\tuserStatsAccount = this.driftClient.userStats?.getAccount();\n\t\t} catch (error) {\n\t\t\t// ignore\n\t\t}\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: userStatsAccount,\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a RevenueShareEscrow account for the user.\n\t *\n\t * @param params - The parameters for creating a RevenueShareEscrow account\n\t * @returns Promise resolving to the transaction signature of the creation\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.createRevenueShareEscrow({\n\t * numOrders: 16,\n\t * builder: {\n\t * builderAuthority: new PublicKey(\"builderAuthority\"),\n\t * maxFeeTenthBps: 100,\n\t * },\n\t * });\n\t * ```\n\t */\n\tasync createRevenueShareEscrow(\n\t\tparams: CreateRevenueShareEscrowParams\n\t): Promise<TransactionSignature> {\n\t\tconst txn = await createRevenueShareEscrowTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\tnumOrders: params.numOrders ?? 16,\n\t\t\tbuilder: params.builder,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserPublicKey: user.userClient.userAccountPublicKey,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\torderIds,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
@@ -48,6 +48,7 @@ export type PerpOrderParams = {
48
48
  direction: PositionDirection;
49
49
  assetType: 'base' | 'quote';
50
50
  size: BigNum;
51
+ positionMaxLeverage: number;
51
52
  reduceOnly?: boolean;
52
53
  postOnly?: PostOnlyParams;
53
54
  isMaxLeverage?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBigNum,\n\tPositionDirection,\n\tPostOnlyParams,\n\tPublicKey,\n\tQuoteResponse,\n} from '@drift-labs/sdk';\nimport { OptionalAuctionParamsRequestInputs } from '../../../../base/actions/trade/openPerpOrder/dlobServer';\nimport { SwiftOrderOptions } from '../../../../base/actions/trade/openPerpOrder/openSwiftOrder';\n\n/**\n * Interface for deposit operation parameters.\n */\nexport interface DepositParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisMaxBorrowRepayment?: boolean;\n}\n\n/**\n * Interface for withdraw operation parameters.\n */\nexport interface WithdrawParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisBorrow?: boolean;\n\tisMax?: boolean;\n}\n\n/**\n * Interface for create user and deposit operation parameters.\n */\nexport interface CreateUserAndDepositParams {\n\tdepositAmount: BigNum;\n\tdepositSpotMarketIndex: number;\n\tnewAccountName?: string;\n\tmaxLeverage?: number;\n\tpoolId?: number;\n\tsubAccountId?: number;\n\treferrerName?: string;\n}\n\nexport interface CreateRevenueShareEscrowParams {\n\tnumOrders?: number;\n\tbuilder?: {\n\t\tbuilderAuthority: PublicKey;\n\t\tmaxFeeTenthBps: number;\n\t};\n}\n\n/**\n * Interface for perp market order parameters.\n */\nexport type PerpOrderParams = {\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tassetType: 'base' | 'quote';\n\tsize: BigNum;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tisMaxLeverage?: boolean;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now (market and limit orders with Swift enabled).\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\torderConfig:\n\t\t| {\n\t\t\t\torderType: 'market';\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\t\t\t\tpostOnly?: never;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'limit';\n\t\t\t\tlimitPrice: BigNum;\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'takeProfit' | 'stopLoss';\n\t\t\t\ttriggerPrice: BigNum;\n\t\t\t\tlimitPrice?: BigNum;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'oracleLimit';\n\t\t\t\toraclePriceOffset: BigNum;\n\t\t };\n};\n\n/**\n * Interface for swap operation parameters.\n */\nexport interface SwapParams {\n\tfromMarketIndex: number;\n\ttoMarketIndex: number;\n\tamount: BigNum;\n\tsubAccountId: number;\n\tjupiterQuote?: QuoteResponse;\n}\n\n/**\n * Interface for settle account P&Ls.\n */\nexport interface SettleAccountPnlParams {\n\tsubAccountId: number;\n}\n\nexport interface CancelOrdersParams {\n\tsubAccountId: number;\n\torderIds: number[];\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBigNum,\n\tPositionDirection,\n\tPostOnlyParams,\n\tPublicKey,\n\tQuoteResponse,\n} from '@drift-labs/sdk';\nimport { OptionalAuctionParamsRequestInputs } from '../../../../base/actions/trade/openPerpOrder/dlobServer';\nimport { SwiftOrderOptions } from '../../../../base/actions/trade/openPerpOrder/openSwiftOrder';\n\n/**\n * Interface for deposit operation parameters.\n */\nexport interface DepositParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisMaxBorrowRepayment?: boolean;\n}\n\n/**\n * Interface for withdraw operation parameters.\n */\nexport interface WithdrawParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisBorrow?: boolean;\n\tisMax?: boolean;\n}\n\n/**\n * Interface for create user and deposit operation parameters.\n */\nexport interface CreateUserAndDepositParams {\n\tdepositAmount: BigNum;\n\tdepositSpotMarketIndex: number;\n\tnewAccountName?: string;\n\tmaxLeverage?: number;\n\tpoolId?: number;\n\tsubAccountId?: number;\n\treferrerName?: string;\n}\n\nexport interface CreateRevenueShareEscrowParams {\n\tnumOrders?: number;\n\tbuilder?: {\n\t\tbuilderAuthority: PublicKey;\n\t\tmaxFeeTenthBps: number;\n\t};\n}\n\n/**\n * Interface for perp market order parameters.\n */\nexport type PerpOrderParams = {\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tassetType: 'base' | 'quote';\n\tsize: BigNum;\n\tpositionMaxLeverage: number;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tisMaxLeverage?: boolean;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now (market and limit orders with Swift enabled).\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\torderConfig:\n\t\t| {\n\t\t\t\torderType: 'market';\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\t\t\t\tpostOnly?: never;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'limit';\n\t\t\t\tlimitPrice: BigNum;\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'takeProfit' | 'stopLoss';\n\t\t\t\ttriggerPrice: BigNum;\n\t\t\t\tlimitPrice?: BigNum;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'oracleLimit';\n\t\t\t\toraclePriceOffset: BigNum;\n\t\t };\n};\n\n/**\n * Interface for swap operation parameters.\n */\nexport interface SwapParams {\n\tfromMarketIndex: number;\n\ttoMarketIndex: number;\n\tamount: BigNum;\n\tsubAccountId: number;\n\tjupiterQuote?: QuoteResponse;\n}\n\n/**\n * Interface for settle account P&Ls.\n */\nexport interface SettleAccountPnlParams {\n\tsubAccountId: number;\n}\n\nexport interface CancelOrdersParams {\n\tsubAccountId: number;\n\torderIds: number[];\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { BN, DriftClient, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, TxParams, User } from '@drift-labs/sdk';
1
+ import { BN, DriftClient, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PriorityFeeSubscriberConfig, PublicKey, QuoteResponse, SwapMode, TxParams, User } from '@drift-labs/sdk';
2
2
  import { Transaction, VersionedTransaction } from '@solana/web3.js';
3
3
  import { CentralServerGetOpenPerpMarketOrderTxnParams, CentralServerGetOpenPerpNonMarketOrderTxnParams } from './types';
4
4
  import { CentralServerDriftMarkets } from './markets';
@@ -15,6 +15,10 @@ export declare class CentralServerDrift {
15
15
  * The public endpoints that can be used to retrieve Drift data / interact with the Drift program.
16
16
  */
17
17
  private _driftEndpoints;
18
+ /**
19
+ * Handles priority fee tracking and calculation for optimized transaction costs.
20
+ */
21
+ private priorityFeeSubscriber;
18
22
  readonly markets: CentralServerDriftMarkets;
19
23
  /**
20
24
  * @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.
@@ -28,6 +32,7 @@ export declare class CentralServerDrift {
28
32
  supportedPerpMarkets: number[];
29
33
  supportedSpotMarkets: number[];
30
34
  additionalDriftClientConfig?: Partial<Omit<DriftClientConfig, 'env'>>;
35
+ priorityFeeSubscriberConfig?: Partial<PriorityFeeSubscriberConfig>;
31
36
  });
32
37
  get driftClient(): DriftClient;
33
38
  subscribe(): Promise<void>;
@@ -53,6 +58,11 @@ export declare class CentralServerDrift {
53
58
  * @param userAccountPublicKey - The user account public key
54
59
  */
55
60
  getUser(userAccountPublicKey: PublicKey): Promise<User>;
61
+ /**
62
+ * Gets transaction parameters with dynamic priority fees.
63
+ * Falls back to default if priority fee function is not available.
64
+ */
65
+ getTxParams(overrides?: Partial<TxParams>): TxParams;
56
66
  getCreateAndDepositTxn(authority: PublicKey, amount: BN, spotMarketIndex: number, options?: {
57
67
  referrerName?: string;
58
68
  accountName?: string;
@@ -67,6 +77,11 @@ export declare class CentralServerDrift {
67
77
  }>;
68
78
  getDepositTxn(userAccountPublicKey: PublicKey, amount: BN, spotMarketIndex: number, options?: {
69
79
  txParams?: TxParams;
80
+ /**
81
+ * Optional external wallet to deposit from. If provided, the deposit will be made
82
+ * from this wallet instead of the user's authority wallet.
83
+ */
84
+ externalWallet?: PublicKey;
70
85
  }): Promise<VersionedTransaction | Transaction>;
71
86
  getDeleteUserTxn(userAccountPublicKey: PublicKey, options?: {
72
87
  txParams?: TxParams;
@@ -107,6 +122,7 @@ export declare class CentralServerDrift {
107
122
  bitFlags?: number;
108
123
  maxTs?: BN;
109
124
  policy?: number;
125
+ positionMaxLeverage?: number;
110
126
  }): Promise<VersionedTransaction | Transaction>;
111
127
  /**
112
128
  * Create a transaction to cancel specific orders by their IDs