@drift-labs/common 1.0.59 → 1.0.61

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 (284) hide show
  1. package/lib/_deprecated/common-math.d.ts +10 -0
  2. package/lib/_deprecated/common-math.js +9 -0
  3. package/lib/_deprecated/common-math.js.map +1 -0
  4. package/lib/_deprecated/common-ui-utils.d.ts +248 -0
  5. package/lib/_deprecated/common-ui-utils.js +59 -0
  6. package/lib/_deprecated/common-ui-utils.js.map +1 -0
  7. package/lib/_deprecated/equality-checks.d.ts +2 -0
  8. package/lib/_deprecated/equality-checks.js +7 -0
  9. package/lib/_deprecated/equality-checks.js.map +1 -0
  10. package/lib/{common-ui-utils/market.d.ts → _deprecated/market-utils.d.ts} +5 -7
  11. package/lib/_deprecated/market-utils.js +18 -0
  12. package/lib/_deprecated/market-utils.js.map +1 -0
  13. package/lib/_deprecated/order-utils.d.ts +12 -0
  14. package/lib/_deprecated/order-utils.js +18 -0
  15. package/lib/_deprecated/order-utils.js.map +1 -0
  16. package/lib/_deprecated/trading-utils.d.ts +52 -0
  17. package/lib/_deprecated/trading-utils.js +27 -0
  18. package/lib/_deprecated/trading-utils.js.map +1 -0
  19. package/lib/_deprecated/user-utils.d.ts +17 -0
  20. package/lib/_deprecated/user-utils.js +12 -0
  21. package/lib/_deprecated/user-utils.js.map +1 -0
  22. package/lib/_deprecated/utils.d.ts +40 -0
  23. package/lib/_deprecated/utils.js +47 -0
  24. package/lib/_deprecated/utils.js.map +1 -0
  25. package/lib/clients/tvFeed.js +2 -2
  26. package/lib/clients/tvFeed.js.map +1 -1
  27. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -8
  28. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  29. package/lib/drift/Drift/clients/AuthorityDrift/index.js +9 -9
  30. package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
  31. package/lib/drift/Drift/clients/CentralServerDrift/index.js +5 -4
  32. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  33. package/lib/drift/base/actions/trade/editOrder.d.ts +1 -1
  34. package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
  35. package/lib/drift/base/actions/trade/margin.js +4 -4
  36. package/lib/drift/base/actions/trade/margin.js.map +1 -1
  37. package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +1 -1
  38. package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -3
  39. package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
  40. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +2 -2
  41. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
  42. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +2 -2
  43. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
  44. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +1 -1
  45. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +4 -4
  46. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  47. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +4 -4
  48. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +60 -32
  49. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  50. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +4 -3
  51. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  52. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +2 -2
  53. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -1
  54. package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +5 -0
  55. package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
  56. package/lib/drift/base/actions/user/create.js +2 -2
  57. package/lib/drift/base/actions/user/create.js.map +1 -1
  58. package/lib/drift/base/details/user/balances.js +2 -2
  59. package/lib/drift/base/details/user/balances.js.map +1 -1
  60. package/lib/drift/base/details/user/positions.js +2 -2
  61. package/lib/drift/base/details/user/positions.js.map +1 -1
  62. package/lib/index.d.ts +28 -28
  63. package/lib/index.js +44 -29
  64. package/lib/index.js.map +1 -1
  65. package/lib/utils/accounts/index.d.ts +6 -0
  66. package/lib/utils/accounts/index.js +23 -0
  67. package/lib/utils/accounts/index.js.map +1 -0
  68. package/lib/utils/accounts/init.d.ts +22 -0
  69. package/lib/utils/accounts/init.js +90 -0
  70. package/lib/utils/accounts/init.js.map +1 -0
  71. package/lib/utils/accounts/keys.d.ts +22 -0
  72. package/lib/utils/accounts/keys.js +36 -0
  73. package/lib/utils/accounts/keys.js.map +1 -0
  74. package/lib/utils/accounts/multiple.d.ts +14 -0
  75. package/lib/utils/accounts/multiple.js +45 -0
  76. package/lib/utils/accounts/multiple.js.map +1 -0
  77. package/lib/utils/accounts/signature.d.ts +6 -0
  78. package/lib/utils/accounts/signature.js +53 -0
  79. package/lib/utils/accounts/signature.js.map +1 -0
  80. package/lib/utils/accounts/subaccounts.d.ts +8 -0
  81. package/lib/utils/accounts/subaccounts.js +31 -0
  82. package/lib/utils/accounts/subaccounts.js.map +1 -0
  83. package/lib/utils/{WalletConnectionState.d.ts → accounts/wallet.d.ts} +7 -1
  84. package/lib/utils/{WalletConnectionState.js → accounts/wallet.js} +32 -2
  85. package/lib/utils/accounts/wallet.js.map +1 -0
  86. package/lib/utils/core/arrays.d.ts +2 -0
  87. package/lib/utils/core/arrays.js +25 -0
  88. package/lib/utils/core/arrays.js.map +1 -0
  89. package/lib/utils/core/async.d.ts +5 -0
  90. package/lib/utils/core/async.js +17 -0
  91. package/lib/utils/core/async.js.map +1 -0
  92. package/lib/utils/core/cache.d.ts +1 -0
  93. package/lib/utils/core/cache.js +40 -0
  94. package/lib/utils/core/cache.js.map +1 -0
  95. package/lib/utils/core/data-structures.d.ts +30 -0
  96. package/lib/utils/core/data-structures.js +84 -0
  97. package/lib/utils/core/data-structures.js.map +1 -0
  98. package/lib/utils/{equalityChecks.d.ts → core/equality.d.ts} +1 -1
  99. package/lib/utils/{equalityChecks.js → core/equality.js} +3 -3
  100. package/lib/utils/core/equality.js.map +1 -0
  101. package/lib/utils/core/fetch.js.map +1 -0
  102. package/lib/utils/core/index.d.ts +7 -0
  103. package/lib/utils/core/index.js +24 -0
  104. package/lib/utils/core/index.js.map +1 -0
  105. package/lib/utils/core/serialization.d.ts +30 -0
  106. package/lib/utils/core/serialization.js +92 -0
  107. package/lib/utils/core/serialization.js.map +1 -0
  108. package/lib/utils/{enum.js → enum/index.js} +1 -1
  109. package/lib/utils/enum/index.js.map +1 -0
  110. package/lib/utils/index.d.ts +11 -176
  111. package/lib/utils/index.js +25 -594
  112. package/lib/utils/index.js.map +1 -1
  113. package/lib/utils/markets/balances.d.ts +6 -0
  114. package/lib/utils/markets/balances.js +29 -0
  115. package/lib/utils/markets/balances.js.map +1 -0
  116. package/lib/utils/markets/config.d.ts +5 -0
  117. package/lib/utils/markets/config.js +24 -0
  118. package/lib/utils/markets/config.js.map +1 -0
  119. package/lib/utils/markets/index.d.ts +6 -0
  120. package/lib/utils/markets/index.js +23 -0
  121. package/lib/utils/markets/index.js.map +1 -0
  122. package/lib/utils/markets/interest.d.ts +25 -0
  123. package/lib/utils/markets/interest.js +65 -0
  124. package/lib/utils/markets/interest.js.map +1 -0
  125. package/lib/utils/markets/leverage.d.ts +12 -0
  126. package/lib/utils/markets/leverage.js +60 -0
  127. package/lib/utils/markets/leverage.js.map +1 -0
  128. package/lib/utils/markets/operations.d.ts +21 -0
  129. package/lib/utils/markets/operations.js +59 -0
  130. package/lib/utils/markets/operations.js.map +1 -0
  131. package/lib/utils/math/bignum.d.ts +3 -0
  132. package/lib/utils/math/bignum.js +16 -0
  133. package/lib/utils/math/bignum.js.map +1 -0
  134. package/lib/utils/math/bn.d.ts +7 -0
  135. package/lib/utils/math/bn.js +58 -0
  136. package/lib/utils/math/bn.js.map +1 -0
  137. package/lib/utils/math/index.d.ts +7 -0
  138. package/lib/utils/math/index.js +24 -0
  139. package/lib/utils/math/index.js.map +1 -0
  140. package/lib/utils/math/numbers.d.ts +13 -0
  141. package/lib/utils/math/numbers.js +56 -0
  142. package/lib/utils/math/numbers.js.map +1 -0
  143. package/lib/utils/math/precision.d.ts +19 -0
  144. package/lib/utils/math/precision.js +73 -0
  145. package/lib/utils/math/precision.js.map +1 -0
  146. package/lib/utils/math/price.d.ts +12 -0
  147. package/lib/utils/math/price.js +45 -0
  148. package/lib/utils/math/price.js.map +1 -0
  149. package/lib/utils/math/sort.d.ts +13 -0
  150. package/lib/utils/math/sort.js +33 -0
  151. package/lib/utils/math/sort.js.map +1 -0
  152. package/lib/utils/math/spread.d.ts +8 -0
  153. package/lib/utils/math/spread.js +87 -0
  154. package/lib/utils/math/spread.js.map +1 -0
  155. package/lib/utils/orderbook/index.js +4 -4
  156. package/lib/utils/orderbook/index.js.map +1 -1
  157. package/lib/utils/orders/filters.d.ts +7 -0
  158. package/lib/utils/orders/filters.js +31 -0
  159. package/lib/utils/orders/filters.js.map +1 -0
  160. package/lib/utils/orders/flags.d.ts +12 -0
  161. package/lib/utils/orders/flags.js +44 -0
  162. package/lib/utils/orders/flags.js.map +1 -0
  163. package/lib/utils/orders/index.d.ts +6 -0
  164. package/lib/utils/orders/index.js +23 -0
  165. package/lib/utils/orders/index.js.map +1 -0
  166. package/lib/utils/orders/labels.d.ts +4 -0
  167. package/lib/utils/orders/labels.js +122 -0
  168. package/lib/utils/orders/labels.js.map +1 -0
  169. package/lib/utils/orders/misc.d.ts +11 -0
  170. package/lib/utils/orders/misc.js +27 -0
  171. package/lib/utils/orders/misc.js.map +1 -0
  172. package/lib/utils/orders/oracle.d.ts +5 -0
  173. package/lib/utils/orders/oracle.js +23 -0
  174. package/lib/utils/orders/oracle.js.map +1 -0
  175. package/lib/utils/orders/sort.d.ts +38 -0
  176. package/lib/utils/orders/sort.js +83 -0
  177. package/lib/utils/orders/sort.js.map +1 -0
  178. package/lib/utils/positions/index.d.ts +2 -0
  179. package/lib/{common-ui-utils → utils/positions}/index.js +1 -5
  180. package/lib/utils/positions/index.js.map +1 -0
  181. package/lib/utils/positions/open.d.ts +4 -0
  182. package/lib/{common-ui-utils/user.js → utils/positions/open.js} +10 -81
  183. package/lib/utils/positions/open.js.map +1 -0
  184. package/lib/utils/positions/user.d.ts +37 -0
  185. package/lib/utils/positions/user.js +74 -0
  186. package/lib/utils/positions/user.js.map +1 -0
  187. package/lib/utils/settings/settings.js.map +1 -0
  188. package/lib/utils/strings/convert.d.ts +11 -0
  189. package/lib/utils/{strings.js → strings/convert.js} +2 -51
  190. package/lib/utils/strings/convert.js.map +1 -0
  191. package/lib/utils/strings/format.d.ts +14 -0
  192. package/lib/utils/strings/format.js +61 -0
  193. package/lib/utils/strings/format.js.map +1 -0
  194. package/lib/utils/strings/index.d.ts +4 -0
  195. package/lib/utils/strings/index.js +21 -0
  196. package/lib/utils/strings/index.js.map +1 -0
  197. package/lib/utils/strings/parse.d.ts +4 -0
  198. package/lib/utils/strings/parse.js +25 -0
  199. package/lib/utils/strings/parse.js.map +1 -0
  200. package/lib/utils/strings/status.d.ts +15 -0
  201. package/lib/utils/strings/status.js +21 -0
  202. package/lib/utils/strings/status.js.map +1 -0
  203. package/lib/utils/token/account.d.ts +16 -0
  204. package/lib/utils/token/account.js +36 -0
  205. package/lib/utils/token/account.js.map +1 -0
  206. package/lib/utils/{token.d.ts → token/address.d.ts} +2 -7
  207. package/lib/utils/token/address.js +30 -0
  208. package/lib/utils/token/address.js.map +1 -0
  209. package/lib/utils/token/index.d.ts +3 -0
  210. package/lib/utils/token/index.js +20 -0
  211. package/lib/utils/token/index.js.map +1 -0
  212. package/lib/utils/token/instructions.d.ts +3 -0
  213. package/lib/utils/token/instructions.js +17 -0
  214. package/lib/utils/token/instructions.js.map +1 -0
  215. package/lib/utils/trading/auction.d.ts +82 -0
  216. package/lib/utils/trading/auction.js +208 -0
  217. package/lib/utils/trading/auction.js.map +1 -0
  218. package/lib/utils/trading/index.d.ts +7 -0
  219. package/lib/utils/trading/index.js +24 -0
  220. package/lib/utils/trading/index.js.map +1 -0
  221. package/lib/utils/trading/leverage.d.ts +18 -0
  222. package/lib/utils/trading/leverage.js +79 -0
  223. package/lib/utils/trading/leverage.js.map +1 -0
  224. package/lib/utils/trading/liquidation.d.ts +22 -0
  225. package/lib/utils/trading/liquidation.js +67 -0
  226. package/lib/utils/trading/liquidation.js.map +1 -0
  227. package/lib/utils/trading/lp.d.ts +4 -0
  228. package/lib/utils/trading/lp.js +20 -0
  229. package/lib/utils/trading/lp.js.map +1 -0
  230. package/lib/utils/trading/pnl.d.ts +34 -0
  231. package/lib/utils/trading/pnl.js +88 -0
  232. package/lib/utils/trading/pnl.js.map +1 -0
  233. package/lib/utils/trading/price.d.ts +12 -0
  234. package/lib/utils/trading/price.js +36 -0
  235. package/lib/utils/trading/price.js.map +1 -0
  236. package/lib/utils/trading/size.d.ts +27 -0
  237. package/lib/utils/trading/size.js +83 -0
  238. package/lib/utils/trading/size.js.map +1 -0
  239. package/lib/utils/{validation.d.ts → validation/address.d.ts} +1 -2
  240. package/lib/utils/{validation.js → validation/address.js} +4 -6
  241. package/lib/utils/validation/address.js.map +1 -0
  242. package/lib/utils/validation/index.d.ts +3 -0
  243. package/lib/utils/validation/index.js +20 -0
  244. package/lib/utils/validation/index.js.map +1 -0
  245. package/lib/utils/validation/input.d.ts +3 -0
  246. package/lib/utils/validation/input.js +33 -0
  247. package/lib/utils/validation/input.js.map +1 -0
  248. package/lib/utils/validation/notional.d.ts +2 -0
  249. package/lib/utils/validation/notional.js +8 -0
  250. package/lib/utils/validation/notional.js.map +1 -0
  251. package/package.json +90 -3
  252. package/lib/common-ui-utils/commonUiUtils.d.ts +0 -251
  253. package/lib/common-ui-utils/commonUiUtils.js +0 -647
  254. package/lib/common-ui-utils/commonUiUtils.js.map +0 -1
  255. package/lib/common-ui-utils/index.d.ts +0 -6
  256. package/lib/common-ui-utils/index.js.map +0 -1
  257. package/lib/common-ui-utils/market.js +0 -134
  258. package/lib/common-ui-utils/market.js.map +0 -1
  259. package/lib/common-ui-utils/order.d.ts +0 -25
  260. package/lib/common-ui-utils/order.js +0 -191
  261. package/lib/common-ui-utils/order.js.map +0 -1
  262. package/lib/common-ui-utils/settings/settings.js.map +0 -1
  263. package/lib/common-ui-utils/trading.d.ts +0 -79
  264. package/lib/common-ui-utils/trading.js +0 -313
  265. package/lib/common-ui-utils/trading.js.map +0 -1
  266. package/lib/common-ui-utils/user.d.ts +0 -18
  267. package/lib/common-ui-utils/user.js.map +0 -1
  268. package/lib/utils/WalletConnectionState.js.map +0 -1
  269. package/lib/utils/enum.js.map +0 -1
  270. package/lib/utils/equalityChecks.js.map +0 -1
  271. package/lib/utils/fetch.js.map +0 -1
  272. package/lib/utils/math.d.ts +0 -31
  273. package/lib/utils/math.js +0 -181
  274. package/lib/utils/math.js.map +0 -1
  275. package/lib/utils/strings.d.ts +0 -34
  276. package/lib/utils/strings.js.map +0 -1
  277. package/lib/utils/token.js +0 -45
  278. package/lib/utils/token.js.map +0 -1
  279. package/lib/utils/validation.js.map +0 -1
  280. /package/lib/utils/{fetch.d.ts → core/fetch.d.ts} +0 -0
  281. /package/lib/utils/{fetch.js → core/fetch.js} +0 -0
  282. /package/lib/utils/{enum.d.ts → enum/index.d.ts} +0 -0
  283. /package/lib/{common-ui-utils → utils}/settings/settings.d.ts +0 -0
  284. /package/lib/{common-ui-utils → utils}/settings/settings.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAMyB;AACzB,yCAOyB;AACzB,mDAGiC;AACjC,uEAO+C;AAC/C,mDAAmD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AG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AA9GW,QAAA,yBAAyB,6BA8GpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tOrderType,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport {\n\tENUM_UTILS,\n\tgetSwiftConfirmationTimeoutMs,\n} from '../../../../../../utils';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\nimport { TRADING_UTILS } from '../../../../../../common-ui-utils/trading';\nimport { Connection } from '@solana/web3.js';\n\n/**\n * Buffer slots to account for signing of message by the user (default: 7 slots ~3 second, assumes user have to approves the signing in a UI wallet).\n */\nexport const USER_SIGNING_MESSAGE_BUFFER_SLOTS = 7;\n\n/**\n * Orders without auction require a higher buffer (kink of the SWIFT server handling non-auction orders)\n */\nexport const MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\n/**\n * Buffer slots from the end of the auction to prevent the signing of the order message.\n */\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\ttakerAuthority: PublicKey;\n\t\tsigningAuthority?: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: number;\n\tisDelegate?: boolean;\n\t/**\n\t * Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t */\n\tconfirmationMultiplier?: number;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n\t/**\n\t * Used for internal tracking of the source of the swift order.\n\t */\n\tsource?: string;\n}\n\n/**\n * Represents a prepared SWIFT order message that is ready to be signed and sent.\n * This is the output of the \"prep\" step, before signing occurs.\n *\n * Consumers should:\n * 1. Sign `hexEncodedSwiftOrderMessage.uInt8Array` with the user's wallet\n * 2. Send the signed message along with the other fields to the SWIFT server\n */\nexport interface SwiftOrderMessage {\n\t/** The encoded order message in both Uint8Array (for signing) and string (for sending) formats */\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\t/** The order parameters message that was encoded */\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\t/** The slot number used for the signed message */\n\tslotForSignedMsg: BN;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** The market index this order is for */\n\tmarketIndex: number;\n\t/** Number of slots till the auction ends (used for confirmation timeout) */\n\tslotsTillAuctionEnd: number;\n\t/** Time in milliseconds before the signing window expires */\n\texpirationTimeMs: number;\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\t/** Optional max leverage for the position */\n\t\tpositionMaxLeverage?: number;\n\t\t/** Optional isolated position deposit amount */\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: number;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t * This is the position (0-indexed) of the builder in the RevenueShareEscrow.approved_builders array.\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\t * Examples:\n\t\t * - 10 = 1 bps = 0.01%\n\t\t * - 50 = 5 bps = 0.05%\n\t\t * - 100 = 10 bps = 0.1%\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param userSigningSlotBuffer - Buffer slots to account for the user to sign the message. Affects the auction start slot. If order is not an auction order, it is not encouraged to use this buffer.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tuserSigningSlotBuffer,\n\tbuilderParams,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n\tresolvedUserSigningSlotBuffer: number;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\tif (!userSigningSlotBuffer) {\n\t\tuserSigningSlotBuffer = mainOrderParams.auctionDuration\n\t\t\t? USER_SIGNING_MESSAGE_BUFFER_SLOTS\n\t\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\t}\n\n\t// if it is not an auction order, there should be a minimum buffer used\n\tif (!mainOrderParams.auctionDuration) {\n\t\tuserSigningSlotBuffer = Math.max(\n\t\t\tuserSigningSlotBuffer,\n\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t);\n\t}\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst auctionStartSlot = new BN(currentSlot + userSigningSlotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconsole.log(\n\t\t'DEBUG swift prep orderParams.isolatedPositionDeposit',\n\t\torderParams.isolatedPositionDeposit?.toString()\n\t);\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: auctionStartSlot,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\tmaxMarginRatio: orderParams.positionMaxLeverage\n\t\t\t? TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\t\t\torderParams.positionMaxLeverage\n\t\t\t )\n\t\t\t: null,\n\t\tisolatedPositionDeposit: orderParams.isolatedPositionDeposit ?? null,\n\t\t// Include builder params if provided\n\t\tbuilderIdx: builderParams?.builderIdx ?? null,\n\t\tbuilderFeeTenthBps: builderParams?.builderFeeTenthBps ?? null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg: auctionStartSlot,\n\t\tsignedMsgOrderUuid,\n\t\tresolvedUserSigningSlotBuffer: userSigningSlotBuffer,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Number of slots till the end of the auction (optional) */\n\tslotsTillAuctionEnd: number;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order) */\n\tconfirmationMultiplier?: number;\n\t/** Optionally send a different connection for the confirmation step, possibly for a faster commitment */\n\tconfirmationConnection?: Connection;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param slotsTillAuctionEnd - Number of slots till the end of the auction (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tslotsTillAuctionEnd,\n\tconfirmationMultiplier,\n\tconfirmationConnection,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tconfirmationConnection ?? driftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\tgetSwiftConfirmationTimeoutMs(slotsTillAuctionEnd, confirmationMultiplier),\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\n/**\n * Computes the timing parameters for a SWIFT order:\n * - slotsTillAuctionEnd: how many slots until the auction is considered ended\n * - expirationTimeMs: how long (in ms) the user has to sign before the window expires\n *\n * For market orders, auction duration + signing buffer is used directly.\n * For non-market orders, a minimum is enforced because limit auctions can have\n * very small durations but the order is still valid after the auction ends.\n */\nconst computeSwiftOrderTiming = (\n\tmainOrderParams: OptionalOrderParams,\n\tuserSigningSlotBuffer: number\n): { slotsTillAuctionEnd: number; expirationTimeMs: number } => {\n\tconst isMarketOrder =\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.ORACLE) ||\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.MARKET);\n\tconst slotsTillAuctionEnd = mainOrderParams.auctionDuration\n\t\t? isMarketOrder\n\t\t\t? userSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t: Math.max(\n\t\t\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\t\t\tuserSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t )\n\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotsTillAuctionEnd - SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\treturn { slotsTillAuctionEnd, expirationTimeMs };\n};\n\ntype PrepSwiftOrderMessageParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tisDelegate?: boolean;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\tpositionMaxLeverage?: number;\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n};\n\n/**\n * Prepares a SWIFT order message without signing or sending it.\n * Returns all data needed for the consumer to sign and send the order themselves.\n *\n * This is useful for server-side contexts (e.g., CentralServerDrift) where\n * the server prepares the message but the client handles signing and sending.\n */\nexport const prepSwiftOrderMessage = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tuserSigningSlotBuffer,\n\tisDelegate = false,\n\torderParams,\n\tbuilderParams,\n}: PrepSwiftOrderMessageParams): Promise<SwiftOrderMessage> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tresolvedUserSigningSlotBuffer,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate,\n\t\torderParams,\n\t\tuserSigningSlotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tconst { slotsTillAuctionEnd, expirationTimeMs } = computeSwiftOrderTiming(\n\t\torderParams.main,\n\t\tresolvedUserSigningSlotBuffer\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t\tmarketIndex,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t};\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t *\n\t * Higher multiplier means longer confirmation timeout.\n\t */\n\tconfirmationMultiplier?: number;\n\tconfirmationConnection?: Connection;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/**\n\t\t * Adjusts the max leverage of a position.\n\t\t */\n\t\tpositionMaxLeverage?: number;\n\t\t/**\n\t\t * Optional isolated position deposit amount for isolated positions.\n\t\t */\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tuserSigningSlotBuffer,\n\tswiftOptions,\n\torderParams,\n\tbuilderParams,\n\tconfirmationMultiplier,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t} = await prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId,\n\t\tuserAccountPubKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl, swiftOptions.source ?? '');\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.takerAuthority,\n\t\tsigningAuthority:\n\t\t\tswiftOptions.wallet.signingAuthority ??\n\t\t\tswiftOptions.wallet.takerAuthority,\n\t\tslotsTillAuctionEnd,\n\t\tconfirmationMultiplier,\n\t\tconfirmationConnection: new Connection(\n\t\t\tdriftClient.connection.rpcEndpoint,\n\t\t\t'processed'\n\t\t),\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAMyB;AACzB,yCAOyB;AACzB,mDAAqD;AACrD,mEAAmF;AACnF,uEAO+C;AAC/C,mDAAmD;AAGnD,+EAA4E;AAC5E,6CAA6C;AAE7C;;GAEG;AACU,QAAA,iCAAiC,GAAG,CAAC,CAAC;AAEnD;;GAEG;AACU,QAAA,+DAA+D,GAAG,EAAE,CAAC;AAElF;;GAEG;AACU,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAqJrE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EAC9B,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,WAAW,EACX,qBAAqB,EACrB,aAAa,GACS,EAWrB,EAAE;;IACH,MAAM,eAAe,GAAG,IAAA,oBAAc,EAAC;QACtC,GAAG,WAAW,CAAC,IAAI;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Message,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { getSwiftConfirmationTimeoutMs } from '../../../../../../utils/signedMsgs';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\nimport { TRADING_UTILS } from '../../../../../../_deprecated/trading-utils';\nimport { Connection } from '@solana/web3.js';\n\n/**\n * Buffer slots to account for signing of message by the user (default: 7 slots ~3 second, assumes user have to approves the signing in a UI wallet).\n */\nexport const USER_SIGNING_MESSAGE_BUFFER_SLOTS = 7;\n\n/**\n * Orders without auction require a higher buffer (kink of the SWIFT server handling non-auction orders)\n */\nexport const MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\n/**\n * Buffer slots from the end of the auction to prevent the signing of the order message.\n */\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\ttakerAuthority: PublicKey;\n\t\tsigningAuthority?: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: number;\n\tisDelegate?: boolean;\n\t/**\n\t * Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t */\n\tconfirmationMultiplier?: number;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n\t/**\n\t * Used for internal tracking of the source of the swift order.\n\t */\n\tsource?: string;\n}\n\n/**\n * Represents a prepared SWIFT order message that is ready to be signed and sent.\n * This is the output of the \"prep\" step, before signing occurs.\n *\n * Consumers should:\n * 1. Sign `hexEncodedSwiftOrderMessage.uInt8Array` with the user's wallet\n * 2. Send the signed message along with the other fields to the SWIFT server\n */\nexport interface SwiftOrderMessage {\n\t/** The encoded order message in both Uint8Array (for signing) and string (for sending) formats */\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\t/** The order parameters message that was encoded */\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\t/** The slot number used for the signed message */\n\tslotForSignedMsg: BN;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** The market index this order is for */\n\tmarketIndex: number;\n\t/** Number of slots till the auction ends (used for confirmation timeout) */\n\tslotsTillAuctionEnd: number;\n\t/** Time in milliseconds before the signing window expires */\n\texpirationTimeMs: number;\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\t/** Optional max leverage for the position */\n\t\tpositionMaxLeverage?: number;\n\t\t/** Optional isolated position deposit amount */\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: number;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t * This is the position (0-indexed) of the builder in the RevenueShareEscrow.approved_builders array.\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\t * Examples:\n\t\t * - 10 = 1 bps = 0.01%\n\t\t * - 50 = 5 bps = 0.05%\n\t\t * - 100 = 10 bps = 0.1%\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param userSigningSlotBuffer - Buffer slots to account for the user to sign the message. Affects the auction start slot. If order is not an auction order, it is not encouraged to use this buffer.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tuserSigningSlotBuffer,\n\tbuilderParams,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n\tresolvedUserSigningSlotBuffer: number;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\tif (!userSigningSlotBuffer) {\n\t\tuserSigningSlotBuffer = mainOrderParams.auctionDuration\n\t\t\t? USER_SIGNING_MESSAGE_BUFFER_SLOTS\n\t\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\t}\n\n\t// if it is not an auction order, there should be a minimum buffer used\n\tif (!mainOrderParams.auctionDuration) {\n\t\tuserSigningSlotBuffer = Math.max(\n\t\t\tuserSigningSlotBuffer,\n\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t);\n\t}\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst auctionStartSlot = new BN(currentSlot + userSigningSlotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconsole.log(\n\t\t'DEBUG swift prep orderParams.isolatedPositionDeposit',\n\t\torderParams.isolatedPositionDeposit?.toString()\n\t);\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: auctionStartSlot,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\tmaxMarginRatio: orderParams.positionMaxLeverage\n\t\t\t? TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\t\t\torderParams.positionMaxLeverage\n\t\t\t )\n\t\t\t: null,\n\t\tisolatedPositionDeposit: orderParams.isolatedPositionDeposit ?? null,\n\t\t// Include builder params if provided\n\t\tbuilderIdx: builderParams?.builderIdx ?? null,\n\t\tbuilderFeeTenthBps: builderParams?.builderFeeTenthBps ?? null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg: auctionStartSlot,\n\t\tsignedMsgOrderUuid,\n\t\tresolvedUserSigningSlotBuffer: userSigningSlotBuffer,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Number of slots till the end of the auction (optional) */\n\tslotsTillAuctionEnd: number;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order) */\n\tconfirmationMultiplier?: number;\n\t/** Optionally send a different connection for the confirmation step, possibly for a faster commitment */\n\tconfirmationConnection?: Connection;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param slotsTillAuctionEnd - Number of slots till the end of the auction (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tslotsTillAuctionEnd,\n\tconfirmationMultiplier,\n\tconfirmationConnection,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tconfirmationConnection ?? driftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\tgetSwiftConfirmationTimeoutMs(slotsTillAuctionEnd, confirmationMultiplier),\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\n/**\n * Computes the timing parameters for a SWIFT order:\n * - slotsTillAuctionEnd: how many slots until the auction is considered ended\n * - expirationTimeMs: how long (in ms) the user has to sign before the window expires\n *\n * For market orders, auction duration + signing buffer is used directly.\n * For non-market orders, a minimum is enforced because limit auctions can have\n * very small durations but the order is still valid after the auction ends.\n */\nconst computeSwiftOrderTiming = (\n\tmainOrderParams: OptionalOrderParams,\n\tuserSigningSlotBuffer: number\n): { slotsTillAuctionEnd: number; expirationTimeMs: number } => {\n\tconst isMarketOrder =\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.ORACLE) ||\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.MARKET);\n\tconst slotsTillAuctionEnd = mainOrderParams.auctionDuration\n\t\t? isMarketOrder\n\t\t\t? userSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t: Math.max(\n\t\t\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\t\t\tuserSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t )\n\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotsTillAuctionEnd - SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\treturn { slotsTillAuctionEnd, expirationTimeMs };\n};\n\ntype PrepSwiftOrderMessageParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tisDelegate?: boolean;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\tpositionMaxLeverage?: number;\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n};\n\n/**\n * Prepares a SWIFT order message without signing or sending it.\n * Returns all data needed for the consumer to sign and send the order themselves.\n *\n * This is useful for server-side contexts (e.g., CentralServerDrift) where\n * the server prepares the message but the client handles signing and sending.\n */\nexport const prepSwiftOrderMessage = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tuserSigningSlotBuffer,\n\tisDelegate = false,\n\torderParams,\n\tbuilderParams,\n}: PrepSwiftOrderMessageParams): Promise<SwiftOrderMessage> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tresolvedUserSigningSlotBuffer,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate,\n\t\torderParams,\n\t\tuserSigningSlotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tconst { slotsTillAuctionEnd, expirationTimeMs } = computeSwiftOrderTiming(\n\t\torderParams.main,\n\t\tresolvedUserSigningSlotBuffer\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t\tmarketIndex,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t};\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t *\n\t * Higher multiplier means longer confirmation timeout.\n\t */\n\tconfirmationMultiplier?: number;\n\tconfirmationConnection?: Connection;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/**\n\t\t * Adjusts the max leverage of a position.\n\t\t */\n\t\tpositionMaxLeverage?: number;\n\t\t/**\n\t\t * Optional isolated position deposit amount for isolated positions.\n\t\t */\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tuserSigningSlotBuffer,\n\tswiftOptions,\n\torderParams,\n\tbuilderParams,\n\tconfirmationMultiplier,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t} = await prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId,\n\t\tuserAccountPubKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl, swiftOptions.source ?? '');\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.takerAuthority,\n\t\tsigningAuthority:\n\t\t\tswiftOptions.wallet.signingAuthority ??\n\t\t\tswiftOptions.wallet.takerAuthority,\n\t\tslotsTillAuctionEnd,\n\t\tconfirmationMultiplier,\n\t\tconfirmationConnection: new Connection(\n\t\t\tdriftClient.connection.rpcEndpoint,\n\t\t\t'processed'\n\t\t),\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getPositionMaxLeverageIxIfNeeded = void 0;
4
- const trading_1 = require("../../../../../common-ui-utils/trading");
4
+ const trading_utils_1 = require("../../../../../_deprecated/trading-utils");
5
5
  /**
6
6
  * Helper function to determine if leverage needs updating and create the instruction if needed.
7
7
  * Returns the instruction to update position max leverage, or undefined if no update is needed.
@@ -14,7 +14,7 @@ async function getPositionMaxLeverageIxIfNeeded(driftClient, user, marketIndex,
14
14
  const userAccount = user.getUserAccount();
15
15
  const currentPosition = userAccount.perpPositions.find((pos) => pos.marketIndex === marketIndex);
16
16
  // Convert leverage to margin ratio
17
- const targetMarginRatio = trading_1.TRADING_UTILS.convertLeverageToMarginRatio(positionMaxLeverage);
17
+ const targetMarginRatio = trading_utils_1.TRADING_UTILS.convertLeverageToMarginRatio(positionMaxLeverage);
18
18
  // Check if leverage needs updating
19
19
  const currentMarginRatio = (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.maxMarginRatio) || 0;
20
20
  // Only create instruction if:
@@ -1 +1 @@
1
- {"version":3,"file":"positionMaxLeverage.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.ts"],"names":[],"mappings":";;;AAEA,oEAAuE;AAEvE;;;GAGG;AACI,KAAK,UAAU,gCAAgC,CACrD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,mBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,oCAAoC;IACpC,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;IAC1C,MAAM,eAAe,GAAG,WAAW,CAAC,aAAa,CAAC,IAAI,CACrD,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,KAAK,WAAW,CACxC,CAAC;IAEF,mCAAmC;IACnC,MAAM,iBAAiB,GACtB,uBAAa,CAAC,4BAA4B,CAAC,mBAAmB,CAAC,CAAC;IAEjE,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,CAAA,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,cAAc,KAAI,CAAC,CAAC;IAEhE,8BAA8B;IAC9B,2CAA2C;IAC3C,2FAA2F;IAC3F,IAAI,iBAAiB,IAAI,iBAAiB,KAAK,kBAAkB,EAAE,CAAC;QACnE,OAAO,MAAM,WAAW,CAAC,4CAA4C,CACpE,WAAW,EACX,iBAAiB,EACjB,WAAW,CAAC,YAAY,EACxB;YACC,oBAAoB,EAAE,IAAI,CAAC,uBAAuB,EAAE;YACpD,SAAS,EAAE,WAAW,CAAC,SAAS;YAChC,gBAAgB;SAChB,CACD,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAzCD,4EAyCC","sourcesContent":["import { DriftClient, User } from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\n\n/**\n * Helper function to determine if leverage needs updating and create the instruction if needed.\n * Returns the instruction to update position max leverage, or undefined if no update is needed.\n */\nexport async function getPositionMaxLeverageIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tpositionMaxLeverage?: number,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!positionMaxLeverage) {\n\t\treturn undefined;\n\t}\n\n\t// Get current position if it exists\n\tconst userAccount = user.getUserAccount();\n\tconst currentPosition = userAccount.perpPositions.find(\n\t\t(pos) => pos.marketIndex === marketIndex\n\t);\n\n\t// Convert leverage to margin ratio\n\tconst targetMarginRatio =\n\t\tTRADING_UTILS.convertLeverageToMarginRatio(positionMaxLeverage);\n\n\t// Check if leverage needs updating\n\tconst currentMarginRatio = currentPosition?.maxMarginRatio || 0;\n\n\t// Only create instruction if:\n\t// 1. We have a target leverage to set, AND\n\t// 2. Either there's no position yet (currentMarginRatio === 0) OR the margin ratios differ\n\tif (targetMarginRatio && targetMarginRatio !== currentMarginRatio) {\n\t\treturn await driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(\n\t\t\tmarketIndex,\n\t\t\ttargetMarginRatio,\n\t\t\tuserAccount.subAccountId,\n\t\t\t{\n\t\t\t\tuserAccountPublicKey: user.getUserAccountPublicKey(),\n\t\t\t\tauthority: userAccount.authority,\n\t\t\t\tsigningAuthority,\n\t\t\t}\n\t\t);\n\t}\n\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"positionMaxLeverage.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.ts"],"names":[],"mappings":";;;AAEA,4EAAyE;AAEzE;;;GAGG;AACI,KAAK,UAAU,gCAAgC,CACrD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,mBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,oCAAoC;IACpC,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;IAC1C,MAAM,eAAe,GAAG,WAAW,CAAC,aAAa,CAAC,IAAI,CACrD,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,KAAK,WAAW,CACxC,CAAC;IAEF,mCAAmC;IACnC,MAAM,iBAAiB,GACtB,6BAAa,CAAC,4BAA4B,CAAC,mBAAmB,CAAC,CAAC;IAEjE,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,CAAA,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,cAAc,KAAI,CAAC,CAAC;IAEhE,8BAA8B;IAC9B,2CAA2C;IAC3C,2FAA2F;IAC3F,IAAI,iBAAiB,IAAI,iBAAiB,KAAK,kBAAkB,EAAE,CAAC;QACnE,OAAO,MAAM,WAAW,CAAC,4CAA4C,CACpE,WAAW,EACX,iBAAiB,EACjB,WAAW,CAAC,YAAY,EACxB;YACC,oBAAoB,EAAE,IAAI,CAAC,uBAAuB,EAAE;YACpD,SAAS,EAAE,WAAW,CAAC,SAAS;YAChC,gBAAgB;SAChB,CACD,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAzCD,4EAyCC","sourcesContent":["import { DriftClient, User } from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { TRADING_UTILS } from '../../../../../_deprecated/trading-utils';\n\n/**\n * Helper function to determine if leverage needs updating and create the instruction if needed.\n * Returns the instruction to update position max leverage, or undefined if no update is needed.\n */\nexport async function getPositionMaxLeverageIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tpositionMaxLeverage?: number,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!positionMaxLeverage) {\n\t\treturn undefined;\n\t}\n\n\t// Get current position if it exists\n\tconst userAccount = user.getUserAccount();\n\tconst currentPosition = userAccount.perpPositions.find(\n\t\t(pos) => pos.marketIndex === marketIndex\n\t);\n\n\t// Convert leverage to margin ratio\n\tconst targetMarginRatio =\n\t\tTRADING_UTILS.convertLeverageToMarginRatio(positionMaxLeverage);\n\n\t// Check if leverage needs updating\n\tconst currentMarginRatio = currentPosition?.maxMarginRatio || 0;\n\n\t// Only create instruction if:\n\t// 1. We have a target leverage to set, AND\n\t// 2. Either there's no position yet (currentMarginRatio === 0) OR the margin ratios differ\n\tif (targetMarginRatio && targetMarginRatio !== currentMarginRatio) {\n\t\treturn await driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(\n\t\t\tmarketIndex,\n\t\t\ttargetMarginRatio,\n\t\t\tuserAccount.subAccountId,\n\t\t\t{\n\t\t\t\tuserAccountPublicKey: user.getUserAccountPublicKey(),\n\t\t\t\tauthority: userAccount.authority,\n\t\t\t\tsigningAuthority,\n\t\t\t}\n\t\t);\n\t}\n\n\treturn undefined;\n}\n"]}
@@ -62,6 +62,11 @@ export interface LimitOrderParamsOrderConfig {
62
62
  */
63
63
  limitAuction?: LimitAuctionConfig;
64
64
  }
65
+ export interface OracleLimitOrderParamsOrderConfig {
66
+ orderType: Extract<NonMarketOrderType, 'oracleLimit'>;
67
+ oraclePriceOffset: BN;
68
+ }
69
+ export type SwiftLimitOrderParamsOrderConfig = LimitOrderParamsOrderConfig | OracleLimitOrderParamsOrderConfig;
65
70
  export interface NonMarketOrderParamsConfig {
66
71
  marketIndex: number;
67
72
  marketType: MarketType;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBN,\n\tMarketType,\n\tPositionDirection,\n\tPostOnlyParams,\n\tReferrerInfo,\n} from '@drift-labs/sdk';\nimport { Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { OptionalAuctionParamsRequestInputs } from './dlobServer';\nimport { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';\n\nexport type TxnOrSwiftResult<T extends boolean> = T extends true\n\t? void\n\t: Transaction | VersionedTransaction;\n\n/**\n * Represents an additional isolated position deposit needed to top up\n * an under-collateralized isolated position before placing an order.\n */\nexport interface AdditionalIsolatedPositionDeposit {\n\tmarketIndex: number;\n\tamount: BN;\n}\n\n/**\n * Override for isolated position deposits. When provided on order params,\n * skips auto-compute and uses these values directly.\n */\nexport interface IsolatedPositionDepositsOverride {\n\t/** The main deposit amount for this market's isolated position. */\n\tmainDeposit: BN;\n\t/** Additional deposits for other under-collateralized isolated positions. */\n\tadditionalDeposits?: AdditionalIsolatedPositionDeposit[];\n}\n\nexport type PlaceAndTakeParams =\n\t| {\n\t\t\tenable: false;\n\t }\n\t| {\n\t\t\tenable: true;\n\t\t\tauctionDurationPercentage?: number;\n\t\t\treferrerInfo: ReferrerInfo | undefined;\n\t };\n\nexport type NonMarketOrderType =\n\t| 'limit'\n\t| 'takeProfit'\n\t| 'stopLoss'\n\t| 'oracleLimit';\n\nexport interface LimitAuctionConfig {\n\tenable: boolean;\n\tdlobServerHttpUrl: string;\n\tauctionStartPriceOffset: number;\n\toraclePrice?: BN; // used to calculate oracle price bands\n\toptionalLimitAuctionParams?: OptionalAuctionParamsRequestInputs;\n\tusePlaceAndTake?: {\n\t\tenable: boolean;\n\t\treferrerInfo?: ReferrerInfo; // needed for place and take fallback\n\t\tauctionDurationPercentage?: number;\n\t};\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n}\n\nexport interface OptionalTriggerOrderParams {\n\tbaseAssetAmount?: BN;\n\ttriggerPrice: BN;\n\tlimitPrice?: BN;\n\treduceOnly?: boolean;\n}\n\nexport interface LimitOrderParamsOrderConfig {\n\torderType: Extract<NonMarketOrderType, 'limit'>;\n\tlimitPrice: BN;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Limit orders can have an optional auction that allows it to go through the auction process.\n\t * Usually, the auction params are set up to the limit price, to allow for a possible improved\n\t * fill price. This is useful for when a limit order is crossing the orderbook.\n\t */\n\tlimitAuction?: LimitAuctionConfig;\n}\n\nexport interface NonMarketOrderParamsConfig {\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\t/**\n\t * The leverage to be used for this position.\n\t * If different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\torderConfig:\n\t\t| LimitOrderParamsOrderConfig\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'takeProfit' | 'stopLoss'>;\n\t\t\t\ttriggerPrice: BN;\n\t\t\t\tlimitPrice?: BN;\n\t\t }\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'oracleLimit'>;\n\t\t\t\toraclePriceOffset: BN;\n\t\t };\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBN,\n\tMarketType,\n\tPositionDirection,\n\tPostOnlyParams,\n\tReferrerInfo,\n} from '@drift-labs/sdk';\nimport { Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { OptionalAuctionParamsRequestInputs } from './dlobServer';\nimport { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';\n\nexport type TxnOrSwiftResult<T extends boolean> = T extends true\n\t? void\n\t: Transaction | VersionedTransaction;\n\n/**\n * Represents an additional isolated position deposit needed to top up\n * an under-collateralized isolated position before placing an order.\n */\nexport interface AdditionalIsolatedPositionDeposit {\n\tmarketIndex: number;\n\tamount: BN;\n}\n\n/**\n * Override for isolated position deposits. When provided on order params,\n * skips auto-compute and uses these values directly.\n */\nexport interface IsolatedPositionDepositsOverride {\n\t/** The main deposit amount for this market's isolated position. */\n\tmainDeposit: BN;\n\t/** Additional deposits for other under-collateralized isolated positions. */\n\tadditionalDeposits?: AdditionalIsolatedPositionDeposit[];\n}\n\nexport type PlaceAndTakeParams =\n\t| {\n\t\t\tenable: false;\n\t }\n\t| {\n\t\t\tenable: true;\n\t\t\tauctionDurationPercentage?: number;\n\t\t\treferrerInfo: ReferrerInfo | undefined;\n\t };\n\nexport type NonMarketOrderType =\n\t| 'limit'\n\t| 'takeProfit'\n\t| 'stopLoss'\n\t| 'oracleLimit';\n\nexport interface LimitAuctionConfig {\n\tenable: boolean;\n\tdlobServerHttpUrl: string;\n\tauctionStartPriceOffset: number;\n\toraclePrice?: BN; // used to calculate oracle price bands\n\toptionalLimitAuctionParams?: OptionalAuctionParamsRequestInputs;\n\tusePlaceAndTake?: {\n\t\tenable: boolean;\n\t\treferrerInfo?: ReferrerInfo; // needed for place and take fallback\n\t\tauctionDurationPercentage?: number;\n\t};\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n}\n\nexport interface OptionalTriggerOrderParams {\n\tbaseAssetAmount?: BN;\n\ttriggerPrice: BN;\n\tlimitPrice?: BN;\n\treduceOnly?: boolean;\n}\n\nexport interface LimitOrderParamsOrderConfig {\n\torderType: Extract<NonMarketOrderType, 'limit'>;\n\tlimitPrice: BN;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Limit orders can have an optional auction that allows it to go through the auction process.\n\t * Usually, the auction params are set up to the limit price, to allow for a possible improved\n\t * fill price. This is useful for when a limit order is crossing the orderbook.\n\t */\n\tlimitAuction?: LimitAuctionConfig;\n}\n\nexport interface OracleLimitOrderParamsOrderConfig {\n\torderType: Extract<NonMarketOrderType, 'oracleLimit'>;\n\toraclePriceOffset: BN;\n}\n\nexport type SwiftLimitOrderParamsOrderConfig =\n\t| LimitOrderParamsOrderConfig\n\t| OracleLimitOrderParamsOrderConfig;\n\nexport interface NonMarketOrderParamsConfig {\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\t/**\n\t * The leverage to be used for this position.\n\t * If different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\torderConfig:\n\t\t| LimitOrderParamsOrderConfig\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'takeProfit' | 'stopLoss'>;\n\t\t\t\ttriggerPrice: BN;\n\t\t\t\tlimitPrice?: BN;\n\t\t }\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'oracleLimit'>;\n\t\t\t\toraclePriceOffset: BN;\n\t\t };\n}\n"]}
@@ -5,7 +5,7 @@ const sdk_1 = require("@drift-labs/sdk");
5
5
  const token_1 = require("../../../../utils/token");
6
6
  const accountNames_1 = require("../../constants/accountNames");
7
7
  const pools_1 = require("../../../../constants/pools");
8
- const user_1 = require("../../../../common-ui-utils/user");
8
+ const user_utils_1 = require("../../../../_deprecated/user-utils");
9
9
  /**
10
10
  * Creates transaction instructions for initializing a new user account and depositing collateral.
11
11
  *
@@ -45,7 +45,7 @@ const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spot
45
45
  const referrerNameAccountPromise = referrerName
46
46
  ? driftClient.fetchReferrerNameAccount(referrerName)
47
47
  : Promise.resolve(undefined);
48
- const subaccountExistsPromise = user_1.USER_UTILS.checkIfUserAccountExists(driftClient, {
48
+ const subaccountExistsPromise = user_utils_1.USER_UTILS.checkIfUserAccountExists(driftClient, {
49
49
  type: 'subAccountId',
50
50
  subAccountId: nextSubaccountId,
51
51
  authority,
@@ -1 +1 @@
1
- {"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts"],"names":[],"mappings":";;;AAAA,yCAWyB;AACzB,mDAA+E;AAC/E,+DAAgF;AAChF,uDAA2D;AAM3D,2DAA8D;AAqB9D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;;IACJ,MAAM,gBAAgB,GAAG,MAAA,gBAAgB,aAAhB,gBAAgB,uBAA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,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;IACJ,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,YAAY,EAAE,GAChD,MAAM,IAAA,6CAAqC,EAAC;QAC3C,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,gBAAgB;QAChB,YAAY;QACZ,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,oBAAoB;QACpB,cAAc;KACd,CAAC,CAAC;IAEJ,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAE7D,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAChE,CAAC,CAAC;AApCW,QAAA,qCAAqC,yCAoChD","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tgetUserAccountPublicKeySync,\n\tPublicKey,\n\tReferrerInfo,\n\tReferrerNameAccount,\n\tSpotMarketConfig,\n\tTxParams,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\nimport { DEFAULT_ACCOUNT_NAMES_BY_POOL_ID } from '../../constants/accountNames';\nimport { MAIN_POOL_ID } from '../../../../constants/pools';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { USER_UTILS } from '../../../../common-ui-utils/user';\n\ninterface CreateUserAndDepositCollateralBaseIxsParams {\n\tdriftClient: DriftClient;\n\tamount: BN;\n\tspotMarketConfig: SpotMarketConfig;\n\tauthority: PublicKey;\n\tuserStatsAccount: UserStatsAccount | undefined;\n\treferrerName?: string;\n\taccountName?: string;\n\tpoolId?: number;\n\tfromSubAccountId?: number;\n\tcustomMaxMarginRatio?: number;\n\tdelegate?: PublicKey;\n\t/**\n\t * Optional external wallet to deposit from. If provided, the deposit will be made\n\t * from this wallet instead of the authority wallet.\n\t */\n\texternalWallet?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for initializing a new user account and depositing collateral.\n *\n * This function generates the necessary transaction instructions to:\n * 1. Initialize a new user account in the Drift protocol\n * 2. Deposit collateral into the newly created account\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - subAccountId: The ID of the newly created sub-account\n * - userAccountPublicKey: The public key of the created user account\n * - ixs: Array of transaction instructions to execute\n */\nexport const createUserAndDepositCollateralBaseIxs = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\tdelegate,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseIxsParams): Promise<{\n\tsubAccountId: number;\n\tuserAccountPublicKey: PublicKey;\n\tixs: TransactionInstruction[];\n}> => {\n\tconst nextSubaccountId = userStatsAccount?.numberOfSubAccountsCreated ?? 0; // userId is zero indexed\n\n\t// Get the spot market account to determine the correct token program for Token-2022 tokens\n\tconst spotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\n\tif (!spotMarketAccount) {\n\t\tthrow new Error(\n\t\t\t`Spot market account not found for market index ${spotMarketConfig.marketIndex}`\n\t\t);\n\t}\n\n\t// Use external wallet for token address if provided, otherwise use authority\n\tconst depositSourceWallet = externalWallet ?? authority;\n\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(\n\t\t\tspotMarketAccount,\n\t\t\tdepositSourceWallet\n\t\t);\n\tconst referrerNameAccountPromise: Promise<ReferrerNameAccount | undefined> =\n\t\treferrerName\n\t\t\t? driftClient.fetchReferrerNameAccount(referrerName)\n\t\t\t: Promise.resolve(undefined);\n\tconst subaccountExistsPromise = USER_UTILS.checkIfUserAccountExists(\n\t\tdriftClient,\n\t\t{\n\t\t\ttype: 'subAccountId',\n\t\t\tsubAccountId: nextSubaccountId,\n\t\t\tauthority,\n\t\t}\n\t);\n\n\tconst [associatedDepositTokenAddress, referrerNameAccount, subaccountExists] =\n\t\tawait Promise.all([\n\t\t\tassociatedDepositTokenAddressPromise,\n\t\t\treferrerNameAccountPromise,\n\t\t\tsubaccountExistsPromise,\n\t\t]);\n\n\tif (subaccountExists) {\n\t\tthrow new Error('Subaccount already exists');\n\t}\n\n\tconst accountNameToUse =\n\t\taccountName ??\n\t\t(poolId !== MAIN_POOL_ID || nextSubaccountId === 0\n\t\t\t? DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]\n\t\t\t: `Account ${nextSubaccountId}`);\n\n\tconst referrerInfo: ReferrerInfo | undefined = referrerNameAccount\n\t\t? {\n\t\t\t\treferrer: referrerNameAccount.user,\n\t\t\t\treferrerStats: referrerNameAccount.userStats,\n\t\t }\n\t\t: undefined;\n\n\tconst { ixs: createAndDepositIxs, userAccountPublicKey } =\n\t\tawait driftClient.createInitializeUserAccountAndDepositCollateralIxs(\n\t\t\tamount,\n\t\t\tassociatedDepositTokenAddress,\n\t\t\tspotMarketConfig.marketIndex,\n\t\t\tnextSubaccountId,\n\t\t\taccountNameToUse,\n\t\t\tfromSubAccountId,\n\t\t\treferrerInfo,\n\t\t\tZERO,\n\t\t\tcustomMaxMarginRatio,\n\t\t\tpoolId,\n\t\t\texternalWallet ? { externalWallet } : undefined\n\t\t);\n\tconst ixs: TransactionInstruction[] = [...createAndDepositIxs];\n\n\tconst nextSubAccountPublicKey = getUserAccountPublicKeySync(\n\t\tdriftClient.program.programId,\n\t\tauthority,\n\t\tnextSubaccountId\n\t);\n\tconst delegateIx = delegate\n\t\t? await driftClient.getUpdateUserDelegateIx(delegate, {\n\t\t\t\tsubAccountId: nextSubaccountId,\n\t\t\t\tuserAccountPublicKey: nextSubAccountPublicKey,\n\t\t\t\tauthority,\n\t\t })\n\t\t: undefined;\n\n\tif (delegateIx) {\n\t\tixs.push(delegateIx);\n\t}\n\n\treturn {\n\t\tsubAccountId: nextSubaccountId,\n\t\tuserAccountPublicKey,\n\t\tixs,\n\t};\n};\n\ninterface CreateUserAndDepositCollateralBaseTxnParams\n\textends CreateUserAndDepositCollateralBaseIxsParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a new user account and depositing collateral.\n *\n * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:\n * 1. Generates the necessary transaction instructions\n * 2. Builds a complete transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)\n * - userAccountPublicKey: The public key of the created user account\n * - subAccountId: The ID of the newly created sub-account\n */\nexport const createUserAndDepositCollateralBaseTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\ttxParams,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tuserAccountPublicKey: PublicKey;\n\tsubAccountId: number;\n}> => {\n\tconst { ixs, userAccountPublicKey, subAccountId } =\n\t\tawait createUserAndDepositCollateralBaseIxs({\n\t\t\tdriftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tauthority,\n\t\t\tuserStatsAccount,\n\t\t\treferrerName,\n\t\t\taccountName,\n\t\t\tpoolId,\n\t\t\tfromSubAccountId,\n\t\t\tcustomMaxMarginRatio,\n\t\t\texternalWallet,\n\t\t});\n\n\tconst tx = await driftClient.buildTransaction(ixs, txParams);\n\n\treturn { transaction: tx, userAccountPublicKey, subAccountId };\n};\n"]}
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts"],"names":[],"mappings":";;;AAAA,yCAWyB;AACzB,mDAA+E;AAC/E,+DAAgF;AAChF,uDAA2D;AAM3D,mEAAgE;AAqBhE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;;IACJ,MAAM,gBAAgB,GAAG,MAAA,gBAAgB,aAAhB,gBAAgB,uBAAhB,g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,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;IACJ,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,YAAY,EAAE,GAChD,MAAM,IAAA,6CAAqC,EAAC;QAC3C,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,gBAAgB;QAChB,YAAY;QACZ,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,oBAAoB;QACpB,cAAc;KACd,CAAC,CAAC;IAEJ,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAE7D,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAChE,CAAC,CAAC;AApCW,QAAA,qCAAqC,yCAoChD","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tgetUserAccountPublicKeySync,\n\tPublicKey,\n\tReferrerInfo,\n\tReferrerNameAccount,\n\tSpotMarketConfig,\n\tTxParams,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\nimport { DEFAULT_ACCOUNT_NAMES_BY_POOL_ID } from '../../constants/accountNames';\nimport { MAIN_POOL_ID } from '../../../../constants/pools';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { USER_UTILS } from '../../../../_deprecated/user-utils';\n\ninterface CreateUserAndDepositCollateralBaseIxsParams {\n\tdriftClient: DriftClient;\n\tamount: BN;\n\tspotMarketConfig: SpotMarketConfig;\n\tauthority: PublicKey;\n\tuserStatsAccount: UserStatsAccount | undefined;\n\treferrerName?: string;\n\taccountName?: string;\n\tpoolId?: number;\n\tfromSubAccountId?: number;\n\tcustomMaxMarginRatio?: number;\n\tdelegate?: PublicKey;\n\t/**\n\t * Optional external wallet to deposit from. If provided, the deposit will be made\n\t * from this wallet instead of the authority wallet.\n\t */\n\texternalWallet?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for initializing a new user account and depositing collateral.\n *\n * This function generates the necessary transaction instructions to:\n * 1. Initialize a new user account in the Drift protocol\n * 2. Deposit collateral into the newly created account\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - subAccountId: The ID of the newly created sub-account\n * - userAccountPublicKey: The public key of the created user account\n * - ixs: Array of transaction instructions to execute\n */\nexport const createUserAndDepositCollateralBaseIxs = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\tdelegate,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseIxsParams): Promise<{\n\tsubAccountId: number;\n\tuserAccountPublicKey: PublicKey;\n\tixs: TransactionInstruction[];\n}> => {\n\tconst nextSubaccountId = userStatsAccount?.numberOfSubAccountsCreated ?? 0; // userId is zero indexed\n\n\t// Get the spot market account to determine the correct token program for Token-2022 tokens\n\tconst spotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\n\tif (!spotMarketAccount) {\n\t\tthrow new Error(\n\t\t\t`Spot market account not found for market index ${spotMarketConfig.marketIndex}`\n\t\t);\n\t}\n\n\t// Use external wallet for token address if provided, otherwise use authority\n\tconst depositSourceWallet = externalWallet ?? authority;\n\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(\n\t\t\tspotMarketAccount,\n\t\t\tdepositSourceWallet\n\t\t);\n\tconst referrerNameAccountPromise: Promise<ReferrerNameAccount | undefined> =\n\t\treferrerName\n\t\t\t? driftClient.fetchReferrerNameAccount(referrerName)\n\t\t\t: Promise.resolve(undefined);\n\tconst subaccountExistsPromise = USER_UTILS.checkIfUserAccountExists(\n\t\tdriftClient,\n\t\t{\n\t\t\ttype: 'subAccountId',\n\t\t\tsubAccountId: nextSubaccountId,\n\t\t\tauthority,\n\t\t}\n\t);\n\n\tconst [associatedDepositTokenAddress, referrerNameAccount, subaccountExists] =\n\t\tawait Promise.all([\n\t\t\tassociatedDepositTokenAddressPromise,\n\t\t\treferrerNameAccountPromise,\n\t\t\tsubaccountExistsPromise,\n\t\t]);\n\n\tif (subaccountExists) {\n\t\tthrow new Error('Subaccount already exists');\n\t}\n\n\tconst accountNameToUse =\n\t\taccountName ??\n\t\t(poolId !== MAIN_POOL_ID || nextSubaccountId === 0\n\t\t\t? DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]\n\t\t\t: `Account ${nextSubaccountId}`);\n\n\tconst referrerInfo: ReferrerInfo | undefined = referrerNameAccount\n\t\t? {\n\t\t\t\treferrer: referrerNameAccount.user,\n\t\t\t\treferrerStats: referrerNameAccount.userStats,\n\t\t }\n\t\t: undefined;\n\n\tconst { ixs: createAndDepositIxs, userAccountPublicKey } =\n\t\tawait driftClient.createInitializeUserAccountAndDepositCollateralIxs(\n\t\t\tamount,\n\t\t\tassociatedDepositTokenAddress,\n\t\t\tspotMarketConfig.marketIndex,\n\t\t\tnextSubaccountId,\n\t\t\taccountNameToUse,\n\t\t\tfromSubAccountId,\n\t\t\treferrerInfo,\n\t\t\tZERO,\n\t\t\tcustomMaxMarginRatio,\n\t\t\tpoolId,\n\t\t\texternalWallet ? { externalWallet } : undefined\n\t\t);\n\tconst ixs: TransactionInstruction[] = [...createAndDepositIxs];\n\n\tconst nextSubAccountPublicKey = getUserAccountPublicKeySync(\n\t\tdriftClient.program.programId,\n\t\tauthority,\n\t\tnextSubaccountId\n\t);\n\tconst delegateIx = delegate\n\t\t? await driftClient.getUpdateUserDelegateIx(delegate, {\n\t\t\t\tsubAccountId: nextSubaccountId,\n\t\t\t\tuserAccountPublicKey: nextSubAccountPublicKey,\n\t\t\t\tauthority,\n\t\t })\n\t\t: undefined;\n\n\tif (delegateIx) {\n\t\tixs.push(delegateIx);\n\t}\n\n\treturn {\n\t\tsubAccountId: nextSubaccountId,\n\t\tuserAccountPublicKey,\n\t\tixs,\n\t};\n};\n\ninterface CreateUserAndDepositCollateralBaseTxnParams\n\textends CreateUserAndDepositCollateralBaseIxsParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a new user account and depositing collateral.\n *\n * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:\n * 1. Generates the necessary transaction instructions\n * 2. Builds a complete transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)\n * - userAccountPublicKey: The public key of the created user account\n * - subAccountId: The ID of the newly created sub-account\n */\nexport const createUserAndDepositCollateralBaseTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\ttxParams,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tuserAccountPublicKey: PublicKey;\n\tsubAccountId: number;\n}> => {\n\tconst { ixs, userAccountPublicKey, subAccountId } =\n\t\tawait createUserAndDepositCollateralBaseIxs({\n\t\t\tdriftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tauthority,\n\t\t\tuserStatsAccount,\n\t\t\treferrerName,\n\t\t\taccountName,\n\t\t\tpoolId,\n\t\t\tfromSubAccountId,\n\t\t\tcustomMaxMarginRatio,\n\t\t\texternalWallet,\n\t\t});\n\n\tconst tx = await driftClient.buildTransaction(ixs, txParams);\n\n\treturn { transaction: tx, userAccountPublicKey, subAccountId };\n};\n"]}
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getSpotBalanceInfo = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
- const market_1 = require("../../../../common-ui-utils/market");
5
+ const market_utils_1 = require("../../../../_deprecated/market-utils");
6
6
  /**
7
7
  * Derives essential balance display information from a User's SpotPosition.
8
8
  *
@@ -20,7 +20,7 @@ const market_1 = require("../../../../common-ui-utils/market");
20
20
  * @returns SpotBalanceInfo object containing the three essential balance metrics
21
21
  */
22
22
  const getSpotBalanceInfo = (driftClient, user, marketIndex, oraclePrice) => {
23
- const spotMarketConfig = market_1.MARKET_UTILS.getMarketConfig(driftClient.env, sdk_1.MarketType.SPOT, marketIndex);
23
+ const spotMarketConfig = market_utils_1.MARKET_UTILS.getMarketConfig(driftClient.env, sdk_1.MarketType.SPOT, marketIndex);
24
24
  const baseBalance = user.getTokenAmount(marketIndex);
25
25
  const baseBalanceBigNum = sdk_1.BigNum.from(baseBalance, spotMarketConfig.precisionExp);
26
26
  const notionalBalance = baseBalanceBigNum
@@ -1 +1 @@
1
- {"version":3,"file":"balances.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/balances.ts"],"names":[],"mappings":";;;AAAA,yCAQyB;AACzB,+DAAkE;AA2BlE;;;;;;;;;;;;;;;GAeG;AACI,MAAM,kBAAkB,GAAG,CACjC,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,WAAe,EACG,EAAE;IACpB,MAAM,gBAAgB,GAAG,qBAAY,CAAC,eAAe,CACpD,WAAW,CAAC,GAAG,EACf,gBAAU,CAAC,IAAI,EACf,WAAW,CACX,CAAC;IAEF,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;IACrD,MAAM,iBAAiB,GAAG,YAAM,CAAC,IAAI,CACpC,WAAW,EACX,gBAAgB,CAAC,YAAY,CAC7B,CAAC;IAEF,MAAM,eAAe,GAAG,iBAAiB;SACvC,GAAG,CAAC,YAAM,CAAC,IAAI,CAAC,WAAW,EAAE,yBAAmB,CAAC,CAAC;SAClD,OAAO,CAAC,yBAAmB,CAAC,CAAC;IAE/B,MAAM,QAAQ,GAAG,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACxD,MAAM,gBAAgB,GAAG,YAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,yBAAmB,CAAC,CAAC;IAEpE,OAAO;QACN,WAAW;QACX,WAAW,EAAE,iBAAiB;QAC9B,eAAe;QACf,gBAAgB;KAChB,CAAC;AACH,CAAC,CAAC;AA/BW,QAAA,kBAAkB,sBA+B7B","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tDriftClient,\n\tMarketType,\n\tPRICE_PRECISION_EXP,\n\tQUOTE_PRECISION_EXP,\n\tUser,\n} from '@drift-labs/sdk';\nimport { MARKET_UTILS } from '../../../../common-ui-utils/market';\n\n/**\n * Essential balance information for a spot market position.\n * Contains the three key metrics needed for balance display and analysis.\n */\nexport interface SpotBalanceInfo {\n\tmarketIndex: number;\n\t/**\n\t * Net balance in base asset terms (deposits - borrows).\n\t * Positive values indicate net deposits, negative values indicate net borrows.\n\t */\n\tbaseBalance: BigNum;\n\n\t/**\n\t * USD notional value of the net balance based on oracle price.\n\t * This represents the current market value of the position.\n\t */\n\tnotionalBalance: BigNum;\n\n\t/**\n\t * Oracle price at which this balance would contribute to account liquidation.\n\t * Returns zero if liquidation price cannot be calculated.\n\t */\n\tliquidationPrice: BigNum;\n}\n\n/**\n * Derives essential balance display information from a User's SpotPosition.\n *\n * Key features:\n * - Calculates net balance (deposits minus borrows) in base asset terms\n * - Computes USD notional value using current oracle price\n * - Determines liquidation price for the specific market\n * - Handles edge cases like zero balances and invalid liquidation prices\n *\n * @param driftClient - The DriftClient instance.\n * @param user - The User instance.\n * @param marketIndex - The market index for the spot market.\n * @param oraclePrice - The oracle price for the spot market.\n *\n * @returns SpotBalanceInfo object containing the three essential balance metrics\n */\nexport const getSpotBalanceInfo = (\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\toraclePrice: BN\n): SpotBalanceInfo => {\n\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\tdriftClient.env,\n\t\tMarketType.SPOT,\n\t\tmarketIndex\n\t);\n\n\tconst baseBalance = user.getTokenAmount(marketIndex);\n\tconst baseBalanceBigNum = BigNum.from(\n\t\tbaseBalance,\n\t\tspotMarketConfig.precisionExp\n\t);\n\n\tconst notionalBalance = baseBalanceBigNum\n\t\t.mul(BigNum.from(oraclePrice, PRICE_PRECISION_EXP))\n\t\t.shiftTo(QUOTE_PRECISION_EXP);\n\n\tconst liqPrice = user.spotLiquidationPrice(marketIndex);\n\tconst liquidationPrice = BigNum.from(liqPrice, PRICE_PRECISION_EXP);\n\n\treturn {\n\t\tmarketIndex,\n\t\tbaseBalance: baseBalanceBigNum,\n\t\tnotionalBalance,\n\t\tliquidationPrice,\n\t};\n};\n"]}
1
+ {"version":3,"file":"balances.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/balances.ts"],"names":[],"mappings":";;;AAAA,yCAQyB;AACzB,uEAAoE;AA2BpE;;;;;;;;;;;;;;;GAeG;AACI,MAAM,kBAAkB,GAAG,CACjC,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,WAAe,EACG,EAAE;IACpB,MAAM,gBAAgB,GAAG,2BAAY,CAAC,eAAe,CACpD,WAAW,CAAC,GAAG,EACf,gBAAU,CAAC,IAAI,EACf,WAAW,CACX,CAAC;IAEF,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;IACrD,MAAM,iBAAiB,GAAG,YAAM,CAAC,IAAI,CACpC,WAAW,EACX,gBAAgB,CAAC,YAAY,CAC7B,CAAC;IAEF,MAAM,eAAe,GAAG,iBAAiB;SACvC,GAAG,CAAC,YAAM,CAAC,IAAI,CAAC,WAAW,EAAE,yBAAmB,CAAC,CAAC;SAClD,OAAO,CAAC,yBAAmB,CAAC,CAAC;IAE/B,MAAM,QAAQ,GAAG,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACxD,MAAM,gBAAgB,GAAG,YAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,yBAAmB,CAAC,CAAC;IAEpE,OAAO;QACN,WAAW;QACX,WAAW,EAAE,iBAAiB;QAC9B,eAAe;QACf,gBAAgB;KAChB,CAAC;AACH,CAAC,CAAC;AA/BW,QAAA,kBAAkB,sBA+B7B","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tDriftClient,\n\tMarketType,\n\tPRICE_PRECISION_EXP,\n\tQUOTE_PRECISION_EXP,\n\tUser,\n} from '@drift-labs/sdk';\nimport { MARKET_UTILS } from '../../../../_deprecated/market-utils';\n\n/**\n * Essential balance information for a spot market position.\n * Contains the three key metrics needed for balance display and analysis.\n */\nexport interface SpotBalanceInfo {\n\tmarketIndex: number;\n\t/**\n\t * Net balance in base asset terms (deposits - borrows).\n\t * Positive values indicate net deposits, negative values indicate net borrows.\n\t */\n\tbaseBalance: BigNum;\n\n\t/**\n\t * USD notional value of the net balance based on oracle price.\n\t * This represents the current market value of the position.\n\t */\n\tnotionalBalance: BigNum;\n\n\t/**\n\t * Oracle price at which this balance would contribute to account liquidation.\n\t * Returns zero if liquidation price cannot be calculated.\n\t */\n\tliquidationPrice: BigNum;\n}\n\n/**\n * Derives essential balance display information from a User's SpotPosition.\n *\n * Key features:\n * - Calculates net balance (deposits minus borrows) in base asset terms\n * - Computes USD notional value using current oracle price\n * - Determines liquidation price for the specific market\n * - Handles edge cases like zero balances and invalid liquidation prices\n *\n * @param driftClient - The DriftClient instance.\n * @param user - The User instance.\n * @param marketIndex - The market index for the spot market.\n * @param oraclePrice - The oracle price for the spot market.\n *\n * @returns SpotBalanceInfo object containing the three essential balance metrics\n */\nexport const getSpotBalanceInfo = (\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\toraclePrice: BN\n): SpotBalanceInfo => {\n\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\tdriftClient.env,\n\t\tMarketType.SPOT,\n\t\tmarketIndex\n\t);\n\n\tconst baseBalance = user.getTokenAmount(marketIndex);\n\tconst baseBalanceBigNum = BigNum.from(\n\t\tbaseBalance,\n\t\tspotMarketConfig.precisionExp\n\t);\n\n\tconst notionalBalance = baseBalanceBigNum\n\t\t.mul(BigNum.from(oraclePrice, PRICE_PRECISION_EXP))\n\t\t.shiftTo(QUOTE_PRECISION_EXP);\n\n\tconst liqPrice = user.spotLiquidationPrice(marketIndex);\n\tconst liquidationPrice = BigNum.from(liqPrice, PRICE_PRECISION_EXP);\n\n\treturn {\n\t\tmarketIndex,\n\t\tbaseBalance: baseBalanceBigNum,\n\t\tnotionalBalance,\n\t\tliquidationPrice,\n\t};\n};\n"]}
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getPositionInfo = exports.getPriceBasedPositionInfo = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
- const trading_1 = require("../../../../common-ui-utils/trading");
5
+ const trading_utils_1 = require("../../../../_deprecated/trading-utils");
6
6
  const utils_1 = require("../../../../utils");
7
7
  const constants_1 = require("../../../../constants");
8
8
  /**
@@ -44,7 +44,7 @@ const getPriceBasedPositionInfo = (driftClient, perpPosition, referencePrice, ac
44
44
  }
45
45
  }
46
46
  // position pnl
47
- const positionNotionalPnlBN = trading_1.TRADING_UTILS.calculatePotentialProfit({
47
+ const positionNotionalPnlBN = trading_utils_1.TRADING_UTILS.calculatePotentialProfit({
48
48
  currentPositionSize: baseSizeBigNum,
49
49
  currentPositionDirection: isShortPosition
50
50
  ? sdk_1.PositionDirection.SHORT
@@ -1 +1 @@
1
- {"version":3,"file":"positions.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/positions.ts"],"names":[],"mappings":";;;AAAA,yCAoByB;AACzB,iEAAoE;AACpE,6CAA+C;AAC/C,qDAG+B;AAqB/B;;;;;;;;;;;GAWG;AACI,MAAM,yBAAyB,GAAG,CACxC,WAAwB,EACxB,YAA0B,EAC1B,cAAkB,EAClB,eAAwB,EACC,EAAE;IAC3B,MAAM,EAAE,WAAW,EAAE,GAAG,YAAY,CAAC;IACrC,MAAM,UAAU,GAAG,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACjE,MAAM,oBAAoB,GAAG,YAAM,CAAC,IAAI,CAAC,cAAc,EAAE,yBAAmB,CAAC,CAAC;IAE9E,YAAY;IACZ,MAAM,QAAQ,GAAG,YAAY,CAAC,eAAe,CAAC;IAC9C,MAAM,cAAc,GAAG,YAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,wBAAkB,CAAC,CAAC;IAEvE,cAAc;IACd,MAAM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O;QACN,WAAW;QACX,QAAQ,EAAE,cAAc;QACxB,YAAY,EAAE,kBAAkB;QAChC,SAAS,EAAE,iBAAiB;QAC5B,UAAU,EAAE,gBAAgB;QAC5B,gBAAgB,EAAE,cAAc;QAChC,iBAAiB,EAAE,uBAAuB;QAC1C,WAAW,EAAE;YACZ,WAAW,EAAE,uBAAuB;YACpC,SAAS,EAAE,qBAAqB;SAChC;QACD,SAAS,EAAE,sBAAsB;QACjC,oBAAoB,EAAE,0BAA0B;QAChD,mBAAmB,EAAE,yBAAyB;QAC9C,iBAAiB,EAAE,wBAAwB;QAC3C,iBAAiB,EAAE,uBAAuB;QAC1C,eAAe,EAAE,qBAAqB;KACtC,CAAC;AACH,CAAC,CAAC;AAvGW,QAAA,eAAe,mBAuG1B","sourcesContent":["import {\n\tBASE_PRECISION_EXP,\n\tBN,\n\tBigNum,\n\tContractType,\n\tDriftClient,\n\tMarketStatus,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpPosition,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tcalculateUnsettledFundingPnl,\n} from '@drift-labs/sdk';\nimport { TRADING_UTILS } from '../../../../common-ui-utils/trading';\nimport { ENUM_UTILS } from '../../../../utils';\nimport {\n\tMAX_PREDICTION_PRICE_BIG_NUM,\n\tUSDC_SPOT_MARKET_INDEX,\n} from '../../../../constants';\n\n/**\n * Comprehensive position information derived from a PerpPosition at a specific reference price.\n * This interface contains all the key metrics needed for position display and analysis.\n */\nexport interface PriceBasedPositionInfo {\n\t/**\n\t * Position PnL in notional terms based on the reference price.\n\t * This does NOT include funding PnL - only the price-based profit/loss.\n\t */\n\tpositionNotionalPnl: BigNum;\n\n\t/**\n\t * Position PnL as a percentage.\n\t * For prediction markets: calculated based on price movement relative to entry.\n\t * For regular markets: calculated as (PnL / quote entry amount) * account leverage.\n\t */\n\tpositionPnlPercentage: number;\n}\n\n/**\n * Derives the user-understandable position display information from a User's PerpPosition and the reference price.\n * The reference price can be the mark price or the oracle price.\n *\n * @param driftClient - The DriftClient instance.\n * @param user - The User instance.\n * @param perpPosition - The PerpPosition instance.\n * @param referencePrice - The reference price. This can be the mark price or the oracle price.\n * @param accountLeverage - The account leverage.\n *\n * @returns The PositionDisplayInfo object. Note that position pnl does not include funding pnl.\n */\nexport const getPriceBasedPositionInfo = (\n\tdriftClient: DriftClient,\n\tperpPosition: PerpPosition,\n\treferencePrice: BN,\n\taccountLeverage?: number\n): PriceBasedPositionInfo => {\n\tconst { marketIndex } = perpPosition;\n\tconst perpMarket = driftClient.getPerpMarketAccount(marketIndex);\n\tconst referencePriceBigNum = BigNum.from(referencePrice, PRICE_PRECISION_EXP);\n\n\t// Base Size\n\tconst baseSize = perpPosition.baseAssetAmount;\n\tconst baseSizeBigNum = BigNum.from(baseSize.abs(), BASE_PRECISION_EXP);\n\n\t// Entry Price\n\tconst entryPriceBN = calculateEntryPrice(perpPosition);\n\tconst entryPriceBigNum = BigNum.from(entryPriceBN, PRICE_PRECISION_EXP);\n\n\tconst isShortPosition = baseSize.isNeg();\n\n\t// Market and prediction market detection\n\tconst isPredictionMarket = ENUM_UTILS.match(\n\t\tperpMarket.contractType,\n\t\tContractType.PREDICTION\n\t);\n\n\t// Price calculations\n\t// Handle prediction market resolution prices\n\tif (isPredictionMarket) {\n\t\tconst isResolved =\n\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.SETTLEMENT) ||\n\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.DELISTED);\n\n\t\tif (isResolved) {\n\t\t\tconst resolvedToNo = perpMarket.expiryPrice.lte(\n\t\t\t\tZERO.add(perpMarket.amm.orderTickSize)\n\t\t\t);\n\n\t\t\tconst price = resolvedToNo\n\t\t\t\t? ZERO.mul(PRICE_PRECISION)\n\t\t\t\t: ONE.mul(PRICE_PRECISION);\n\n\t\t\treferencePrice = price;\n\t\t}\n\t}\n\n\t// position pnl\n\tconst positionNotionalPnlBN = TRADING_UTILS.calculatePotentialProfit({\n\t\tcurrentPositionSize: baseSizeBigNum,\n\t\tcurrentPositionDirection: isShortPosition\n\t\t\t? PositionDirection.SHORT\n\t\t\t: PositionDirection.LONG,\n\t\tcurrentPositionEntryPrice: BigNum.from(entryPriceBN, PRICE_PRECISION_EXP),\n\t\ttradeDirection: isShortPosition\n\t\t\t? PositionDirection.LONG\n\t\t\t: PositionDirection.SHORT,\n\t\texitBaseSize: baseSizeBigNum,\n\t\texitPrice: referencePriceBigNum,\n\t\ttakerFeeBps: 0,\n\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\tconst positionNotionalPnlBigNum = BigNum.from(\n\t\tpositionNotionalPnlBN,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\t// Determine if this is a sell-side prediction market for price adjustment\n\tconst isSellPredictionMarket = isPredictionMarket && isShortPosition;\n\n\t// Apply prediction market price adjustment for display\n\tconst markPriceToUseForPredictionMarket = isSellPredictionMarket\n\t\t? MAX_PREDICTION_PRICE_BIG_NUM.sub(referencePriceBigNum).val\n\t\t: referencePrice;\n\n\tconst positionPnlPercentage = isPredictionMarket\n\t\t? BigNum.from(markPriceToUseForPredictionMarket, PRICE_PRECISION_EXP)\n\t\t\t\t.sub(entryPriceBigNum)\n\t\t\t\t.mul(PRICE_PRECISION)\n\t\t\t\t.div(entryPriceBN)\n\t\t\t\t.toNum() *\n\t\t 100 *\n\t\t (isShortPosition ? -1 : 1)\n\t\t: accountLeverage\n\t\t? (() => {\n\t\t\t\tconst quoteAmount = perpPosition.quoteEntryAmount.abs();\n\n\t\t\t\tif (quoteAmount.eq(ZERO)) return 0;\n\n\t\t\t\tconst pnlPct =\n\t\t\t\t\tpositionNotionalPnlBigNum.val\n\t\t\t\t\t\t.mul(new BN(10_000))\n\t\t\t\t\t\t.div(quoteAmount)\n\t\t\t\t\t\t.toNumber() / 1_000_000;\n\t\t\t\treturn pnlPct * (accountLeverage || 1);\n\t\t })()\n\t\t: 0;\n\n\treturn {\n\t\tpositionNotionalPnl: positionNotionalPnlBigNum,\n\t\tpositionPnlPercentage,\n\t};\n};\n\nexport type PerpPositionInfo = {\n\tmarketIndex: number;\n\t/** Absolute base size of the position. */\n\tbaseSize: BigNum;\n\t/** Notional value of the position based on oracle price */\n\tnotionalSize: BigNum;\n\t/** Direction of the position */\n\tdirection: PositionDirection;\n\t/** Position entry price.*/\n\tentryPrice: BigNum;\n\t/**\n\t * Price at which the position would be liquidated.\n\t * Returns zero if liquidation price cannot be calculated.\n\t */\n\tliquidationPrice: BigNum;\n\t/**\n\t * Cumulative funding and fees PnL for this position.\n\t * This is separate from positionNotionalPnl to allow granular PnL breakdown.\n\t */\n\tfeesAndFundingPnl: BigNum;\n\t/** Position P&L information based on the oracle price and the mark price as reference prices. This does not include fees and funding PnL. */\n\tpositionPnl: {\n\t\toracleBased: PriceBasedPositionInfo;\n\t\tmarkBased: PriceBasedPositionInfo;\n\t};\n\t/** The quote amount that was used to enter the position. */\n\tcostBasis: BigNum;\n\t/** The quote amount that the position needs to be at, to breakeven. This is net of fees and funding, hence why it is different from quoteEntryAmount. */\n\tquoteBreakEvenAmount: BigNum;\n\t/** This is the total of unsettled pnl and unsettled funding. */\n\ttotalUnsettledPnl: BigNum;\n\t/** This is the total of unsettled pnl and unsettled funding that is claimable from the P&L pool. */\n\ttotalClaimablePnl: BigNum;\n\t/** This is the unsettled funding pnl. */\n\tunsettledFundingPnl: BigNum;\n\t/** This is the total of settled pnl and settled funding. */\n\ttotalSettledPnl: BigNum;\n};\n\nexport const getPositionInfo = (\n\tdriftClient: DriftClient,\n\tuser: User,\n\tperpPosition: PerpPosition,\n\toraclePrice: BN,\n\tmarkPrice: BN\n): PerpPositionInfo => {\n\tconst { marketIndex } = perpPosition;\n\n\tconst baseSize = perpPosition.baseAssetAmount;\n\tconst baseSizeBigNum = BigNum.from(baseSize.abs(), BASE_PRECISION_EXP);\n\n\tconst notionalSizeBigNum = BigNum.from(\n\t\tuser\n\t\t\t.getPerpPositionValue(perpPosition.marketIndex, {\n\t\t\t\tprice: oraclePrice,\n\t\t\t})\n\t\t\t.abs(),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\tconst positionDirection = baseSize.isNeg()\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tconst entryPrice = calculateEntryPrice(perpPosition);\n\tconst entryPriceBigNum = BigNum.from(entryPrice, PRICE_PRECISION_EXP);\n\n\tconst liqPrice = user.liquidationPrice(marketIndex);\n\tconst liqPriceBigNum = BigNum.from(liqPrice, PRICE_PRECISION_EXP);\n\n\tconst perpMarket = driftClient.getPerpMarketAccount(marketIndex);\n\tconst feesAndFundingPnlBigNum = BigNum.from(\n\t\tcalculateFeesAndFundingPnl(perpMarket, perpPosition),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\tconst accountLeverage = user.getLeverage().toNumber();\n\tconst oracleBasedPositionInfo = getPriceBasedPositionInfo(\n\t\tdriftClient,\n\t\tperpPosition,\n\t\toraclePrice,\n\t\taccountLeverage\n\t);\n\tconst markBasedPositionInfo = getPriceBasedPositionInfo(\n\t\tdriftClient,\n\t\tperpPosition,\n\t\tmarkPrice,\n\t\taccountLeverage\n\t);\n\n\tconst quoteEntryAmountBigNum = BigNum.from(\n\t\tperpPosition.quoteEntryAmount,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst quoteBreakEvenAmountBigNum = BigNum.from(\n\t\tperpPosition.quoteBreakEvenAmount,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\tconst totalUnrealizedPnlBigNum = BigNum.from(\n\t\tcalculatePositionPNL(perpMarket, perpPosition, true, {\n\t\t\tprice: oraclePrice,\n\t\t}),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst usdcSpotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tUSDC_SPOT_MARKET_INDEX\n\t);\n\tconst totalClaimablePnlBigNum = BigNum.from(\n\t\tcalculateClaimablePnl(perpMarket, usdcSpotMarketAccount, perpPosition, {\n\t\t\tprice: oraclePrice,\n\t\t}),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst unsettledFundingPnlBigNum = BigNum.from(\n\t\tcalculateUnsettledFundingPnl(perpMarket, perpPosition),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst totalSettledPnlBigNum = BigNum.from(\n\t\tperpPosition.settledPnl,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\treturn {\n\t\tmarketIndex,\n\t\tbaseSize: baseSizeBigNum,\n\t\tnotionalSize: notionalSizeBigNum,\n\t\tdirection: positionDirection,\n\t\tentryPrice: entryPriceBigNum,\n\t\tliquidationPrice: liqPriceBigNum,\n\t\tfeesAndFundingPnl: feesAndFundingPnlBigNum,\n\t\tpositionPnl: {\n\t\t\toracleBased: oracleBasedPositionInfo,\n\t\t\tmarkBased: markBasedPositionInfo,\n\t\t},\n\t\tcostBasis: quoteEntryAmountBigNum,\n\t\tquoteBreakEvenAmount: quoteBreakEvenAmountBigNum,\n\t\tunsettledFundingPnl: unsettledFundingPnlBigNum,\n\t\ttotalUnsettledPnl: totalUnrealizedPnlBigNum,\n\t\ttotalClaimablePnl: totalClaimablePnlBigNum,\n\t\ttotalSettledPnl: totalSettledPnlBigNum,\n\t};\n};\n"]}
1
+ {"version":3,"file":"positions.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/positions.ts"],"names":[],"mappings":";;;AAAA,yCAoByB;AACzB,yEAAsE;AACtE,6CAA+C;AAC/C,qDAG+B;AAqB/B;;;;;;;;;;;GAWG;AACI,MAAM,yBAAyB,GAAG,CACxC,WAAwB,EACxB,YAA0B,EAC1B,cAAkB,EAClB,eAAwB,EACC,EAAE;IAC3B,MAAM,EAAE,WAAW,EAAE,GAAG,YAAY,CAAC;IACrC,MAAM,UAAU,GAAG,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAA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AK,EAAE,WAAW;KAClB,CAAC,EACF,yBAAmB,CACnB,CAAC;IACF,MAAM,yBAAyB,GAAG,YAAM,CAAC,IAAI,CAC5C,IAAA,kCAA4B,EAAC,UAAU,EAAE,YAAY,CAAC,EACtD,yBAAmB,CACnB,CAAC;IACF,MAAM,qBAAqB,GAAG,YAAM,CAAC,IAAI,CACxC,YAAY,CAAC,UAAU,EACvB,yBAAmB,CACnB,CAAC;IAEF,OAAO;QACN,WAAW;QACX,QAAQ,EAAE,cAAc;QACxB,YAAY,EAAE,kBAAkB;QAChC,SAAS,EAAE,iBAAiB;QAC5B,UAAU,EAAE,gBAAgB;QAC5B,gBAAgB,EAAE,cAAc;QAChC,iBAAiB,EAAE,uBAAuB;QAC1C,WAAW,EAAE;YACZ,WAAW,EAAE,uBAAuB;YACpC,SAAS,EAAE,qBAAqB;SAChC;QACD,SAAS,EAAE,sBAAsB;QACjC,oBAAoB,EAAE,0BAA0B;QAChD,mBAAmB,EAAE,yBAAyB;QAC9C,iBAAiB,EAAE,wBAAwB;QAC3C,iBAAiB,EAAE,uBAAuB;QAC1C,eAAe,EAAE,qBAAqB;KACtC,CAAC;AACH,CAAC,CAAC;AAvGW,QAAA,eAAe,mBAuG1B","sourcesContent":["import {\n\tBASE_PRECISION_EXP,\n\tBN,\n\tBigNum,\n\tContractType,\n\tDriftClient,\n\tMarketStatus,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpPosition,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tcalculateUnsettledFundingPnl,\n} from '@drift-labs/sdk';\nimport { TRADING_UTILS } from '../../../../_deprecated/trading-utils';\nimport { ENUM_UTILS } from '../../../../utils';\nimport {\n\tMAX_PREDICTION_PRICE_BIG_NUM,\n\tUSDC_SPOT_MARKET_INDEX,\n} from '../../../../constants';\n\n/**\n * Comprehensive position information derived from a PerpPosition at a specific reference price.\n * This interface contains all the key metrics needed for position display and analysis.\n */\nexport interface PriceBasedPositionInfo {\n\t/**\n\t * Position PnL in notional terms based on the reference price.\n\t * This does NOT include funding PnL - only the price-based profit/loss.\n\t */\n\tpositionNotionalPnl: BigNum;\n\n\t/**\n\t * Position PnL as a percentage.\n\t * For prediction markets: calculated based on price movement relative to entry.\n\t * For regular markets: calculated as (PnL / quote entry amount) * account leverage.\n\t */\n\tpositionPnlPercentage: number;\n}\n\n/**\n * Derives the user-understandable position display information from a User's PerpPosition and the reference price.\n * The reference price can be the mark price or the oracle price.\n *\n * @param driftClient - The DriftClient instance.\n * @param user - The User instance.\n * @param perpPosition - The PerpPosition instance.\n * @param referencePrice - The reference price. This can be the mark price or the oracle price.\n * @param accountLeverage - The account leverage.\n *\n * @returns The PositionDisplayInfo object. Note that position pnl does not include funding pnl.\n */\nexport const getPriceBasedPositionInfo = (\n\tdriftClient: DriftClient,\n\tperpPosition: PerpPosition,\n\treferencePrice: BN,\n\taccountLeverage?: number\n): PriceBasedPositionInfo => {\n\tconst { marketIndex } = perpPosition;\n\tconst perpMarket = driftClient.getPerpMarketAccount(marketIndex);\n\tconst referencePriceBigNum = BigNum.from(referencePrice, PRICE_PRECISION_EXP);\n\n\t// Base Size\n\tconst baseSize = perpPosition.baseAssetAmount;\n\tconst baseSizeBigNum = BigNum.from(baseSize.abs(), BASE_PRECISION_EXP);\n\n\t// Entry Price\n\tconst entryPriceBN = calculateEntryPrice(perpPosition);\n\tconst entryPriceBigNum = BigNum.from(entryPriceBN, PRICE_PRECISION_EXP);\n\n\tconst isShortPosition = baseSize.isNeg();\n\n\t// Market and prediction market detection\n\tconst isPredictionMarket = ENUM_UTILS.match(\n\t\tperpMarket.contractType,\n\t\tContractType.PREDICTION\n\t);\n\n\t// Price calculations\n\t// Handle prediction market resolution prices\n\tif (isPredictionMarket) {\n\t\tconst isResolved =\n\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.SETTLEMENT) ||\n\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.DELISTED);\n\n\t\tif (isResolved) {\n\t\t\tconst resolvedToNo = perpMarket.expiryPrice.lte(\n\t\t\t\tZERO.add(perpMarket.amm.orderTickSize)\n\t\t\t);\n\n\t\t\tconst price = resolvedToNo\n\t\t\t\t? ZERO.mul(PRICE_PRECISION)\n\t\t\t\t: ONE.mul(PRICE_PRECISION);\n\n\t\t\treferencePrice = price;\n\t\t}\n\t}\n\n\t// position pnl\n\tconst positionNotionalPnlBN = TRADING_UTILS.calculatePotentialProfit({\n\t\tcurrentPositionSize: baseSizeBigNum,\n\t\tcurrentPositionDirection: isShortPosition\n\t\t\t? PositionDirection.SHORT\n\t\t\t: PositionDirection.LONG,\n\t\tcurrentPositionEntryPrice: BigNum.from(entryPriceBN, PRICE_PRECISION_EXP),\n\t\ttradeDirection: isShortPosition\n\t\t\t? PositionDirection.LONG\n\t\t\t: PositionDirection.SHORT,\n\t\texitBaseSize: baseSizeBigNum,\n\t\texitPrice: referencePriceBigNum,\n\t\ttakerFeeBps: 0,\n\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\tconst positionNotionalPnlBigNum = BigNum.from(\n\t\tpositionNotionalPnlBN,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\t// Determine if this is a sell-side prediction market for price adjustment\n\tconst isSellPredictionMarket = isPredictionMarket && isShortPosition;\n\n\t// Apply prediction market price adjustment for display\n\tconst markPriceToUseForPredictionMarket = isSellPredictionMarket\n\t\t? MAX_PREDICTION_PRICE_BIG_NUM.sub(referencePriceBigNum).val\n\t\t: referencePrice;\n\n\tconst positionPnlPercentage = isPredictionMarket\n\t\t? BigNum.from(markPriceToUseForPredictionMarket, PRICE_PRECISION_EXP)\n\t\t\t\t.sub(entryPriceBigNum)\n\t\t\t\t.mul(PRICE_PRECISION)\n\t\t\t\t.div(entryPriceBN)\n\t\t\t\t.toNum() *\n\t\t 100 *\n\t\t (isShortPosition ? -1 : 1)\n\t\t: accountLeverage\n\t\t? (() => {\n\t\t\t\tconst quoteAmount = perpPosition.quoteEntryAmount.abs();\n\n\t\t\t\tif (quoteAmount.eq(ZERO)) return 0;\n\n\t\t\t\tconst pnlPct =\n\t\t\t\t\tpositionNotionalPnlBigNum.val\n\t\t\t\t\t\t.mul(new BN(10_000))\n\t\t\t\t\t\t.div(quoteAmount)\n\t\t\t\t\t\t.toNumber() / 1_000_000;\n\t\t\t\treturn pnlPct * (accountLeverage || 1);\n\t\t })()\n\t\t: 0;\n\n\treturn {\n\t\tpositionNotionalPnl: positionNotionalPnlBigNum,\n\t\tpositionPnlPercentage,\n\t};\n};\n\nexport type PerpPositionInfo = {\n\tmarketIndex: number;\n\t/** Absolute base size of the position. */\n\tbaseSize: BigNum;\n\t/** Notional value of the position based on oracle price */\n\tnotionalSize: BigNum;\n\t/** Direction of the position */\n\tdirection: PositionDirection;\n\t/** Position entry price.*/\n\tentryPrice: BigNum;\n\t/**\n\t * Price at which the position would be liquidated.\n\t * Returns zero if liquidation price cannot be calculated.\n\t */\n\tliquidationPrice: BigNum;\n\t/**\n\t * Cumulative funding and fees PnL for this position.\n\t * This is separate from positionNotionalPnl to allow granular PnL breakdown.\n\t */\n\tfeesAndFundingPnl: BigNum;\n\t/** Position P&L information based on the oracle price and the mark price as reference prices. This does not include fees and funding PnL. */\n\tpositionPnl: {\n\t\toracleBased: PriceBasedPositionInfo;\n\t\tmarkBased: PriceBasedPositionInfo;\n\t};\n\t/** The quote amount that was used to enter the position. */\n\tcostBasis: BigNum;\n\t/** The quote amount that the position needs to be at, to breakeven. This is net of fees and funding, hence why it is different from quoteEntryAmount. */\n\tquoteBreakEvenAmount: BigNum;\n\t/** This is the total of unsettled pnl and unsettled funding. */\n\ttotalUnsettledPnl: BigNum;\n\t/** This is the total of unsettled pnl and unsettled funding that is claimable from the P&L pool. */\n\ttotalClaimablePnl: BigNum;\n\t/** This is the unsettled funding pnl. */\n\tunsettledFundingPnl: BigNum;\n\t/** This is the total of settled pnl and settled funding. */\n\ttotalSettledPnl: BigNum;\n};\n\nexport const getPositionInfo = (\n\tdriftClient: DriftClient,\n\tuser: User,\n\tperpPosition: PerpPosition,\n\toraclePrice: BN,\n\tmarkPrice: BN\n): PerpPositionInfo => {\n\tconst { marketIndex } = perpPosition;\n\n\tconst baseSize = perpPosition.baseAssetAmount;\n\tconst baseSizeBigNum = BigNum.from(baseSize.abs(), BASE_PRECISION_EXP);\n\n\tconst notionalSizeBigNum = BigNum.from(\n\t\tuser\n\t\t\t.getPerpPositionValue(perpPosition.marketIndex, {\n\t\t\t\tprice: oraclePrice,\n\t\t\t})\n\t\t\t.abs(),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\tconst positionDirection = baseSize.isNeg()\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tconst entryPrice = calculateEntryPrice(perpPosition);\n\tconst entryPriceBigNum = BigNum.from(entryPrice, PRICE_PRECISION_EXP);\n\n\tconst liqPrice = user.liquidationPrice(marketIndex);\n\tconst liqPriceBigNum = BigNum.from(liqPrice, PRICE_PRECISION_EXP);\n\n\tconst perpMarket = driftClient.getPerpMarketAccount(marketIndex);\n\tconst feesAndFundingPnlBigNum = BigNum.from(\n\t\tcalculateFeesAndFundingPnl(perpMarket, perpPosition),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\tconst accountLeverage = user.getLeverage().toNumber();\n\tconst oracleBasedPositionInfo = getPriceBasedPositionInfo(\n\t\tdriftClient,\n\t\tperpPosition,\n\t\toraclePrice,\n\t\taccountLeverage\n\t);\n\tconst markBasedPositionInfo = getPriceBasedPositionInfo(\n\t\tdriftClient,\n\t\tperpPosition,\n\t\tmarkPrice,\n\t\taccountLeverage\n\t);\n\n\tconst quoteEntryAmountBigNum = BigNum.from(\n\t\tperpPosition.quoteEntryAmount,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst quoteBreakEvenAmountBigNum = BigNum.from(\n\t\tperpPosition.quoteBreakEvenAmount,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\tconst totalUnrealizedPnlBigNum = BigNum.from(\n\t\tcalculatePositionPNL(perpMarket, perpPosition, true, {\n\t\t\tprice: oraclePrice,\n\t\t}),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst usdcSpotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tUSDC_SPOT_MARKET_INDEX\n\t);\n\tconst totalClaimablePnlBigNum = BigNum.from(\n\t\tcalculateClaimablePnl(perpMarket, usdcSpotMarketAccount, perpPosition, {\n\t\t\tprice: oraclePrice,\n\t\t}),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst unsettledFundingPnlBigNum = BigNum.from(\n\t\tcalculateUnsettledFundingPnl(perpMarket, perpPosition),\n\t\tQUOTE_PRECISION_EXP\n\t);\n\tconst totalSettledPnlBigNum = BigNum.from(\n\t\tperpPosition.settledPnl,\n\t\tQUOTE_PRECISION_EXP\n\t);\n\n\treturn {\n\t\tmarketIndex,\n\t\tbaseSize: baseSizeBigNum,\n\t\tnotionalSize: notionalSizeBigNum,\n\t\tdirection: positionDirection,\n\t\tentryPrice: entryPriceBigNum,\n\t\tliquidationPrice: liqPriceBigNum,\n\t\tfeesAndFundingPnl: feesAndFundingPnlBigNum,\n\t\tpositionPnl: {\n\t\t\toracleBased: oracleBasedPositionInfo,\n\t\t\tmarkBased: markBasedPositionInfo,\n\t\t},\n\t\tcostBasis: quoteEntryAmountBigNum,\n\t\tquoteBreakEvenAmount: quoteBreakEvenAmountBigNum,\n\t\tunsettledFundingPnl: unsettledFundingPnlBigNum,\n\t\ttotalUnsettledPnl: totalUnrealizedPnlBigNum,\n\t\ttotalClaimablePnl: totalClaimablePnlBigNum,\n\t\ttotalSettledPnl: totalSettledPnlBigNum,\n\t};\n};\n"]}
package/lib/index.d.ts CHANGED
@@ -1,49 +1,49 @@
1
- export * from './Config';
2
- export * from './chartConstants';
3
- export * from './types';
4
- export * from './EnvironmentConstants';
5
1
  export * from './utils';
6
- export * from './utils/index';
7
- export * from './utils/s3Buckets';
8
- export * from './serializableTypes';
9
- export * from './utils/candles/Candle';
2
+ export * from './utils/logger';
10
3
  export * from './utils/featureFlags';
11
- export * from './utils/WalletConnectionState';
4
+ export * from './utils/candles/Candle';
12
5
  export * from './utils/rpcLatency';
13
- export * from './utils/token';
14
- export * from './utils/math';
15
- export * from './utils/logger';
16
- export * from './utils/equalityChecks';
17
- export * from './common-ui-utils';
18
- export * from './constants';
19
- export * from './actions/actionHelpers/actionHelpers';
20
6
  export * from './utils/SharedInterval';
21
7
  export * from './utils/Stopwatch';
22
8
  export * from './utils/priority-fees';
23
9
  export * from './utils/superstake';
24
- export * from './utils/fetch';
25
10
  export * from './utils/priceImpact';
26
11
  export * from './utils/dlob-server/DlobServerWebsocketUtils';
27
- export * from './common-ui-utils/settings/settings';
28
- export * from './utils/priority-fees';
29
12
  export * from './utils/orderbook';
30
- export * from './clients/candleClient';
31
- export * from './clients/marketDataFeed';
32
- export * from './clients/swiftClient';
33
- export * from './clients/tvFeed';
34
- export * from './clients/DlobWebsocketClient';
35
13
  export * from './utils/pollingSequenceGuard';
36
14
  export * from './utils/driftEvents';
37
- export * from './utils/MultiplexWebSocket';
38
15
  export * from './utils/SlotBasedResultValidator';
39
16
  export * from './utils/CircularBuffers';
40
17
  export * from './utils/rxjs';
41
18
  export * from './utils/priorityFees';
42
19
  export * from './utils/NumLib';
43
- export * from './utils/strings';
44
- export * from './utils/validation';
20
+ export * from './utils/s3Buckets';
21
+ export * from './utils/insuranceFund';
22
+ export * from './utils/settings/settings';
45
23
  export { default as millify } from './utils/millify';
46
- export * from './utils/markets/precisions';
24
+ export { getSwiftConfirmationTimeoutMs } from './utils/signedMsgs';
25
+ export { ResultSlotIncrementer } from './utils/ResultSlotIncrementer';
26
+ export { MultiplexWebSocket } from './utils/MultiplexWebSocket';
27
+ export { COMMON_UTILS } from './_deprecated/utils';
28
+ export { COMMON_UI_UTILS } from './_deprecated/common-ui-utils';
29
+ export { COMMON_MATH } from './_deprecated/common-math';
30
+ export { EQUALITY_CHECKS } from './_deprecated/equality-checks';
31
+ export { TRADING_UTILS } from './_deprecated/trading-utils';
32
+ export { MARKET_UTILS } from './_deprecated/market-utils';
33
+ export { ORDER_COMMON_UTILS } from './_deprecated/order-utils';
34
+ export { USER_UTILS } from './_deprecated/user-utils';
35
+ export * from './Config';
36
+ export * from './chartConstants';
37
+ export * from './types';
38
+ export * from './EnvironmentConstants';
39
+ export * from './serializableTypes';
40
+ export * from './constants';
41
+ export * from './actions/actionHelpers/actionHelpers';
42
+ export * from './clients/candleClient';
43
+ export * from './clients/marketDataFeed';
44
+ export * from './clients/swiftClient';
45
+ export * from './clients/tvFeed';
46
+ export * from './clients/DlobWebsocketClient';
47
47
  export * from './drift';
48
48
  import JupV4Errors from './constants/autogenerated/jup-v4-error-codes.json';
49
49
  import JupV6Errors from './constants/autogenerated/jup-v6-error-codes.json';