@drift-labs/common 1.0.59 → 1.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/lib/_deprecated/common-math.d.ts +10 -0
  2. package/lib/_deprecated/common-math.js +9 -0
  3. package/lib/_deprecated/common-math.js.map +1 -0
  4. package/lib/_deprecated/common-ui-utils.d.ts +248 -0
  5. package/lib/_deprecated/common-ui-utils.js +59 -0
  6. package/lib/_deprecated/common-ui-utils.js.map +1 -0
  7. package/lib/_deprecated/equality-checks.d.ts +2 -0
  8. package/lib/_deprecated/equality-checks.js +7 -0
  9. package/lib/_deprecated/equality-checks.js.map +1 -0
  10. package/lib/{common-ui-utils/market.d.ts → _deprecated/market-utils.d.ts} +5 -7
  11. package/lib/_deprecated/market-utils.js +18 -0
  12. package/lib/_deprecated/market-utils.js.map +1 -0
  13. package/lib/_deprecated/order-utils.d.ts +12 -0
  14. package/lib/_deprecated/order-utils.js +18 -0
  15. package/lib/_deprecated/order-utils.js.map +1 -0
  16. package/lib/_deprecated/trading-utils.d.ts +52 -0
  17. package/lib/_deprecated/trading-utils.js +27 -0
  18. package/lib/_deprecated/trading-utils.js.map +1 -0
  19. package/lib/_deprecated/user-utils.d.ts +17 -0
  20. package/lib/_deprecated/user-utils.js +12 -0
  21. package/lib/_deprecated/user-utils.js.map +1 -0
  22. package/lib/_deprecated/utils.d.ts +40 -0
  23. package/lib/_deprecated/utils.js +47 -0
  24. package/lib/_deprecated/utils.js.map +1 -0
  25. package/lib/clients/tvFeed.js +2 -2
  26. package/lib/clients/tvFeed.js.map +1 -1
  27. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -8
  28. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  29. package/lib/drift/Drift/clients/AuthorityDrift/index.js +9 -9
  30. package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
  31. package/lib/drift/Drift/clients/CentralServerDrift/index.js +2 -2
  32. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  33. package/lib/drift/base/actions/trade/editOrder.d.ts +1 -1
  34. package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
  35. package/lib/drift/base/actions/trade/margin.js +4 -4
  36. package/lib/drift/base/actions/trade/margin.js.map +1 -1
  37. package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +1 -1
  38. package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -3
  39. package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
  40. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +2 -2
  41. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
  42. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +2 -2
  43. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
  44. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +1 -1
  45. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +4 -4
  46. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  47. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +1 -1
  48. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +2 -2
  49. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  50. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +4 -3
  51. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  52. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +2 -2
  53. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -1
  54. package/lib/drift/base/actions/user/create.js +2 -2
  55. package/lib/drift/base/actions/user/create.js.map +1 -1
  56. package/lib/drift/base/details/user/balances.js +2 -2
  57. package/lib/drift/base/details/user/balances.js.map +1 -1
  58. package/lib/drift/base/details/user/positions.js +2 -2
  59. package/lib/drift/base/details/user/positions.js.map +1 -1
  60. package/lib/index.d.ts +28 -28
  61. package/lib/index.js +44 -29
  62. package/lib/index.js.map +1 -1
  63. package/lib/utils/accounts/index.d.ts +6 -0
  64. package/lib/utils/accounts/index.js +23 -0
  65. package/lib/utils/accounts/index.js.map +1 -0
  66. package/lib/utils/accounts/init.d.ts +22 -0
  67. package/lib/utils/accounts/init.js +90 -0
  68. package/lib/utils/accounts/init.js.map +1 -0
  69. package/lib/utils/accounts/keys.d.ts +22 -0
  70. package/lib/utils/accounts/keys.js +36 -0
  71. package/lib/utils/accounts/keys.js.map +1 -0
  72. package/lib/utils/accounts/multiple.d.ts +14 -0
  73. package/lib/utils/accounts/multiple.js +45 -0
  74. package/lib/utils/accounts/multiple.js.map +1 -0
  75. package/lib/utils/accounts/signature.d.ts +6 -0
  76. package/lib/utils/accounts/signature.js +53 -0
  77. package/lib/utils/accounts/signature.js.map +1 -0
  78. package/lib/utils/accounts/subaccounts.d.ts +8 -0
  79. package/lib/utils/accounts/subaccounts.js +31 -0
  80. package/lib/utils/accounts/subaccounts.js.map +1 -0
  81. package/lib/utils/{WalletConnectionState.d.ts → accounts/wallet.d.ts} +7 -1
  82. package/lib/utils/{WalletConnectionState.js → accounts/wallet.js} +32 -2
  83. package/lib/utils/accounts/wallet.js.map +1 -0
  84. package/lib/utils/core/arrays.d.ts +2 -0
  85. package/lib/utils/core/arrays.js +25 -0
  86. package/lib/utils/core/arrays.js.map +1 -0
  87. package/lib/utils/core/async.d.ts +5 -0
  88. package/lib/utils/core/async.js +17 -0
  89. package/lib/utils/core/async.js.map +1 -0
  90. package/lib/utils/core/cache.d.ts +1 -0
  91. package/lib/utils/core/cache.js +40 -0
  92. package/lib/utils/core/cache.js.map +1 -0
  93. package/lib/utils/core/data-structures.d.ts +30 -0
  94. package/lib/utils/core/data-structures.js +84 -0
  95. package/lib/utils/core/data-structures.js.map +1 -0
  96. package/lib/utils/{equalityChecks.d.ts → core/equality.d.ts} +1 -1
  97. package/lib/utils/{equalityChecks.js → core/equality.js} +3 -3
  98. package/lib/utils/core/equality.js.map +1 -0
  99. package/lib/utils/core/fetch.js.map +1 -0
  100. package/lib/utils/core/index.d.ts +7 -0
  101. package/lib/utils/core/index.js +24 -0
  102. package/lib/utils/core/index.js.map +1 -0
  103. package/lib/utils/core/serialization.d.ts +30 -0
  104. package/lib/utils/core/serialization.js +92 -0
  105. package/lib/utils/core/serialization.js.map +1 -0
  106. package/lib/utils/{enum.js → enum/index.js} +1 -1
  107. package/lib/utils/enum/index.js.map +1 -0
  108. package/lib/utils/index.d.ts +11 -176
  109. package/lib/utils/index.js +25 -594
  110. package/lib/utils/index.js.map +1 -1
  111. package/lib/utils/markets/balances.d.ts +6 -0
  112. package/lib/utils/markets/balances.js +29 -0
  113. package/lib/utils/markets/balances.js.map +1 -0
  114. package/lib/utils/markets/config.d.ts +5 -0
  115. package/lib/utils/markets/config.js +24 -0
  116. package/lib/utils/markets/config.js.map +1 -0
  117. package/lib/utils/markets/index.d.ts +6 -0
  118. package/lib/utils/markets/index.js +23 -0
  119. package/lib/utils/markets/index.js.map +1 -0
  120. package/lib/utils/markets/interest.d.ts +25 -0
  121. package/lib/utils/markets/interest.js +65 -0
  122. package/lib/utils/markets/interest.js.map +1 -0
  123. package/lib/utils/markets/leverage.d.ts +12 -0
  124. package/lib/utils/markets/leverage.js +60 -0
  125. package/lib/utils/markets/leverage.js.map +1 -0
  126. package/lib/utils/markets/operations.d.ts +21 -0
  127. package/lib/utils/markets/operations.js +59 -0
  128. package/lib/utils/markets/operations.js.map +1 -0
  129. package/lib/utils/math/bignum.d.ts +3 -0
  130. package/lib/utils/math/bignum.js +16 -0
  131. package/lib/utils/math/bignum.js.map +1 -0
  132. package/lib/utils/math/bn.d.ts +7 -0
  133. package/lib/utils/math/bn.js +58 -0
  134. package/lib/utils/math/bn.js.map +1 -0
  135. package/lib/utils/math/index.d.ts +7 -0
  136. package/lib/utils/math/index.js +24 -0
  137. package/lib/utils/math/index.js.map +1 -0
  138. package/lib/utils/math/numbers.d.ts +13 -0
  139. package/lib/utils/math/numbers.js +56 -0
  140. package/lib/utils/math/numbers.js.map +1 -0
  141. package/lib/utils/math/precision.d.ts +19 -0
  142. package/lib/utils/math/precision.js +73 -0
  143. package/lib/utils/math/precision.js.map +1 -0
  144. package/lib/utils/math/price.d.ts +12 -0
  145. package/lib/utils/math/price.js +45 -0
  146. package/lib/utils/math/price.js.map +1 -0
  147. package/lib/utils/math/sort.d.ts +13 -0
  148. package/lib/utils/math/sort.js +33 -0
  149. package/lib/utils/math/sort.js.map +1 -0
  150. package/lib/utils/math/spread.d.ts +8 -0
  151. package/lib/utils/math/spread.js +87 -0
  152. package/lib/utils/math/spread.js.map +1 -0
  153. package/lib/utils/orderbook/index.js +4 -4
  154. package/lib/utils/orderbook/index.js.map +1 -1
  155. package/lib/utils/orders/filters.d.ts +7 -0
  156. package/lib/utils/orders/filters.js +31 -0
  157. package/lib/utils/orders/filters.js.map +1 -0
  158. package/lib/utils/orders/flags.d.ts +12 -0
  159. package/lib/utils/orders/flags.js +44 -0
  160. package/lib/utils/orders/flags.js.map +1 -0
  161. package/lib/utils/orders/index.d.ts +6 -0
  162. package/lib/utils/orders/index.js +23 -0
  163. package/lib/utils/orders/index.js.map +1 -0
  164. package/lib/utils/orders/labels.d.ts +4 -0
  165. package/lib/utils/orders/labels.js +122 -0
  166. package/lib/utils/orders/labels.js.map +1 -0
  167. package/lib/utils/orders/misc.d.ts +11 -0
  168. package/lib/utils/orders/misc.js +27 -0
  169. package/lib/utils/orders/misc.js.map +1 -0
  170. package/lib/utils/orders/oracle.d.ts +5 -0
  171. package/lib/utils/orders/oracle.js +23 -0
  172. package/lib/utils/orders/oracle.js.map +1 -0
  173. package/lib/utils/orders/sort.d.ts +38 -0
  174. package/lib/utils/orders/sort.js +83 -0
  175. package/lib/utils/orders/sort.js.map +1 -0
  176. package/lib/utils/positions/index.d.ts +2 -0
  177. package/lib/{common-ui-utils → utils/positions}/index.js +1 -5
  178. package/lib/utils/positions/index.js.map +1 -0
  179. package/lib/utils/positions/open.d.ts +4 -0
  180. package/lib/{common-ui-utils/user.js → utils/positions/open.js} +10 -81
  181. package/lib/utils/positions/open.js.map +1 -0
  182. package/lib/utils/positions/user.d.ts +37 -0
  183. package/lib/utils/positions/user.js +74 -0
  184. package/lib/utils/positions/user.js.map +1 -0
  185. package/lib/utils/settings/settings.js.map +1 -0
  186. package/lib/utils/strings/convert.d.ts +11 -0
  187. package/lib/utils/{strings.js → strings/convert.js} +2 -51
  188. package/lib/utils/strings/convert.js.map +1 -0
  189. package/lib/utils/strings/format.d.ts +14 -0
  190. package/lib/utils/strings/format.js +61 -0
  191. package/lib/utils/strings/format.js.map +1 -0
  192. package/lib/utils/strings/index.d.ts +4 -0
  193. package/lib/utils/strings/index.js +21 -0
  194. package/lib/utils/strings/index.js.map +1 -0
  195. package/lib/utils/strings/parse.d.ts +4 -0
  196. package/lib/utils/strings/parse.js +25 -0
  197. package/lib/utils/strings/parse.js.map +1 -0
  198. package/lib/utils/strings/status.d.ts +15 -0
  199. package/lib/utils/strings/status.js +21 -0
  200. package/lib/utils/strings/status.js.map +1 -0
  201. package/lib/utils/token/account.d.ts +16 -0
  202. package/lib/utils/token/account.js +36 -0
  203. package/lib/utils/token/account.js.map +1 -0
  204. package/lib/utils/{token.d.ts → token/address.d.ts} +2 -7
  205. package/lib/utils/token/address.js +30 -0
  206. package/lib/utils/token/address.js.map +1 -0
  207. package/lib/utils/token/index.d.ts +3 -0
  208. package/lib/utils/token/index.js +20 -0
  209. package/lib/utils/token/index.js.map +1 -0
  210. package/lib/utils/token/instructions.d.ts +3 -0
  211. package/lib/utils/token/instructions.js +17 -0
  212. package/lib/utils/token/instructions.js.map +1 -0
  213. package/lib/utils/trading/auction.d.ts +82 -0
  214. package/lib/utils/trading/auction.js +208 -0
  215. package/lib/utils/trading/auction.js.map +1 -0
  216. package/lib/utils/trading/index.d.ts +7 -0
  217. package/lib/utils/trading/index.js +24 -0
  218. package/lib/utils/trading/index.js.map +1 -0
  219. package/lib/utils/trading/leverage.d.ts +18 -0
  220. package/lib/utils/trading/leverage.js +79 -0
  221. package/lib/utils/trading/leverage.js.map +1 -0
  222. package/lib/utils/trading/liquidation.d.ts +22 -0
  223. package/lib/utils/trading/liquidation.js +67 -0
  224. package/lib/utils/trading/liquidation.js.map +1 -0
  225. package/lib/utils/trading/lp.d.ts +4 -0
  226. package/lib/utils/trading/lp.js +20 -0
  227. package/lib/utils/trading/lp.js.map +1 -0
  228. package/lib/utils/trading/pnl.d.ts +34 -0
  229. package/lib/utils/trading/pnl.js +88 -0
  230. package/lib/utils/trading/pnl.js.map +1 -0
  231. package/lib/utils/trading/price.d.ts +12 -0
  232. package/lib/utils/trading/price.js +36 -0
  233. package/lib/utils/trading/price.js.map +1 -0
  234. package/lib/utils/trading/size.d.ts +27 -0
  235. package/lib/utils/trading/size.js +83 -0
  236. package/lib/utils/trading/size.js.map +1 -0
  237. package/lib/utils/{validation.d.ts → validation/address.d.ts} +1 -2
  238. package/lib/utils/{validation.js → validation/address.js} +4 -6
  239. package/lib/utils/validation/address.js.map +1 -0
  240. package/lib/utils/validation/index.d.ts +3 -0
  241. package/lib/utils/validation/index.js +20 -0
  242. package/lib/utils/validation/index.js.map +1 -0
  243. package/lib/utils/validation/input.d.ts +3 -0
  244. package/lib/utils/validation/input.js +33 -0
  245. package/lib/utils/validation/input.js.map +1 -0
  246. package/lib/utils/validation/notional.d.ts +2 -0
  247. package/lib/utils/validation/notional.js +8 -0
  248. package/lib/utils/validation/notional.js.map +1 -0
  249. package/package.json +90 -3
  250. package/lib/common-ui-utils/commonUiUtils.d.ts +0 -251
  251. package/lib/common-ui-utils/commonUiUtils.js +0 -647
  252. package/lib/common-ui-utils/commonUiUtils.js.map +0 -1
  253. package/lib/common-ui-utils/index.d.ts +0 -6
  254. package/lib/common-ui-utils/index.js.map +0 -1
  255. package/lib/common-ui-utils/market.js +0 -134
  256. package/lib/common-ui-utils/market.js.map +0 -1
  257. package/lib/common-ui-utils/order.d.ts +0 -25
  258. package/lib/common-ui-utils/order.js +0 -191
  259. package/lib/common-ui-utils/order.js.map +0 -1
  260. package/lib/common-ui-utils/settings/settings.js.map +0 -1
  261. package/lib/common-ui-utils/trading.d.ts +0 -79
  262. package/lib/common-ui-utils/trading.js +0 -313
  263. package/lib/common-ui-utils/trading.js.map +0 -1
  264. package/lib/common-ui-utils/user.d.ts +0 -18
  265. package/lib/common-ui-utils/user.js.map +0 -1
  266. package/lib/utils/WalletConnectionState.js.map +0 -1
  267. package/lib/utils/enum.js.map +0 -1
  268. package/lib/utils/equalityChecks.js.map +0 -1
  269. package/lib/utils/fetch.js.map +0 -1
  270. package/lib/utils/math.d.ts +0 -31
  271. package/lib/utils/math.js +0 -181
  272. package/lib/utils/math.js.map +0 -1
  273. package/lib/utils/strings.d.ts +0 -34
  274. package/lib/utils/strings.js.map +0 -1
  275. package/lib/utils/token.js +0 -45
  276. package/lib/utils/token.js.map +0 -1
  277. package/lib/utils/validation.js.map +0 -1
  278. /package/lib/utils/{fetch.d.ts → core/fetch.d.ts} +0 -0
  279. /package/lib/utils/{fetch.js → core/fetch.js} +0 -0
  280. /package/lib/utils/{enum.d.ts → enum/index.d.ts} +0 -0
  281. /package/lib/{common-ui-utils → utils}/settings/settings.d.ts +0 -0
  282. /package/lib/{common-ui-utils → utils}/settings/settings.js +0 -0
@@ -1,79 +0,0 @@
1
- import { BN, BigNum, DriftClient, PositionDirection, User } from '@drift-labs/sdk';
2
- import { MarketId, OpenPosition, UIOrderType } from 'src/types';
3
- /**
4
- * Checks if a given order amount represents an entire position order
5
- * by comparing it with MAX_LEVERAGE_ORDER_SIZE
6
- * @param orderAmount - The BigNum order amount to check
7
- * @returns true if the order is for the entire position, false otherwise
8
- */
9
- export declare const isEntirePositionOrder: (orderAmount: BigNum) => boolean;
10
- /**
11
- * Gets the MAX_LEVERAGE_ORDER_SIZE as a BigNum with the same precision as the given amount
12
- * @param orderAmount - The BigNum order amount to match precision with
13
- * @returns BigNum representation of MAX_LEVERAGE_ORDER_SIZE
14
- */
15
- export declare const getMaxLeverageOrderSize: (orderAmount: BigNum) => BigNum;
16
- /**
17
- * Formats an order size for display, showing "Entire Position" if it's a max leverage order
18
- * @param orderAmount - The BigNum order amount to format
19
- * @param formatFn - Optional custom format function, defaults to prettyPrint()
20
- * @returns Formatted string showing either "Entire Position" or the formatted amount
21
- */
22
- export declare const formatOrderSize: (orderAmount: BigNum, formatFn?: (amount: BigNum) => string) => string;
23
- export declare const TRADING_UTILS: {
24
- calculatePnlPctFromPosition: (pnl: BN, position: OpenPosition, marginUsed?: BN) => number;
25
- calculatePotentialProfit: (props: {
26
- currentPositionSize: BigNum;
27
- currentPositionDirection: PositionDirection;
28
- currentPositionEntryPrice: BigNum;
29
- tradeDirection: PositionDirection;
30
- /**
31
- * Amount of position being closed in base asset size
32
- */
33
- exitBaseSize: BigNum;
34
- /**
35
- * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)
36
- */
37
- exitPrice: BigNum;
38
- takerFeeBps: number;
39
- slippageTolerance?: number;
40
- isMarketOrder?: boolean;
41
- }) => {
42
- estimatedProfit: BigNum;
43
- estimatedProfitBeforeFees: BigNum;
44
- estimatedTakerFee: BigNum;
45
- notionalSizeAtEntry: BigNum;
46
- notionalSizeAtExit: BigNum;
47
- };
48
- calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, marginType, }: {
49
- estEntryPrice: BN;
50
- orderType: UIOrderType;
51
- perpMarketIndex: number;
52
- tradeBaseSize: BN;
53
- isLong: boolean;
54
- userClient: User;
55
- oraclePrice: BN;
56
- limitPrice?: BN;
57
- offsetCollateral?: BN;
58
- precision?: number;
59
- isEnteringHighLeverageMode?: boolean;
60
- capLiqPrice?: boolean;
61
- marginType?: 'Cross' | 'Isolated';
62
- }) => number;
63
- checkIsMarketOrderType: (orderType: UIOrderType) => boolean;
64
- convertLeverageToMarginRatio: (leverage: number) => number | undefined;
65
- convertMarginRatioToLeverage: (marginRatio: number, decimals?: number) => number | undefined;
66
- getMarketTickSize: (driftClient: DriftClient, marketId: MarketId) => BN;
67
- getMarketTickSizeDecimals: (driftClient: DriftClient, marketId: MarketId) => number;
68
- getMarketStepSize: (driftClient: DriftClient, marketId: MarketId) => BN;
69
- getMarketStepSizeDecimals: (driftClient: DriftClient, marketId: MarketId) => number;
70
- isEntirePositionOrder: (orderAmount: BigNum) => boolean;
71
- getMaxLeverageOrderSize: (orderAmount: BigNum) => BigNum;
72
- formatOrderSize: (orderAmount: BigNum, formatFn?: (amount: BigNum) => string) => string;
73
- getMarginUsedForPosition: (user: User, marketIndex: number, includeOpenOrders?: boolean) => BN | undefined;
74
- validateLeverageChange: ({ user, marketIndex, newLeverage, }: {
75
- user: User;
76
- marketIndex: number;
77
- newLeverage: number;
78
- }) => boolean;
79
- };
@@ -1,313 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TRADING_UTILS = exports.formatOrderSize = exports.getMaxLeverageOrderSize = exports.isEntirePositionOrder = void 0;
4
- const sdk_1 = require("@drift-labs/sdk");
5
- const calculatePnlPctFromPosition = (pnl, position, marginUsed) => {
6
- var _a;
7
- if (!(position === null || position === void 0 ? void 0 : position.quoteEntryAmount) || (position === null || position === void 0 ? void 0 : position.quoteEntryAmount.eq(sdk_1.ZERO)))
8
- return 0;
9
- let marginUsedNum;
10
- if (marginUsed) {
11
- marginUsedNum = sdk_1.BigNum.from(marginUsed, sdk_1.QUOTE_PRECISION_EXP).toNum();
12
- }
13
- else {
14
- const leverage = (_a = convertMarginRatioToLeverage(position.maxMarginRatio)) !== null && _a !== void 0 ? _a : 1;
15
- const quoteEntryAmountNum = sdk_1.BigNum.from(position.quoteEntryAmount.abs(), sdk_1.QUOTE_PRECISION_EXP).toNum();
16
- if (leverage <= 0 || quoteEntryAmountNum <= 0) {
17
- marginUsedNum = 0;
18
- }
19
- else {
20
- marginUsedNum = quoteEntryAmountNum / leverage;
21
- }
22
- }
23
- if (marginUsedNum <= 0) {
24
- return 0;
25
- }
26
- return (sdk_1.BigNum.from(pnl, sdk_1.QUOTE_PRECISION_EXP)
27
- .shift(5)
28
- .div(sdk_1.BigNum.fromPrint(`${marginUsedNum}`, sdk_1.QUOTE_PRECISION_EXP))
29
- .toNum() * 100);
30
- };
31
- const POTENTIAL_PROFIT_DEFAULT_STATE = {
32
- estimatedProfit: sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP),
33
- estimatedProfitBeforeFees: sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP),
34
- estimatedTakerFee: sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP),
35
- notionalSizeAtEntry: sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP),
36
- notionalSizeAtExit: sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP),
37
- };
38
- const calculatePotentialProfit = (props) => {
39
- let estimatedProfit = sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP);
40
- let estimatedProfitBeforeFees = sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP);
41
- let estimatedTakerFee = sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP);
42
- let notionalSizeAtEntry = sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP);
43
- let notionalSizeAtExit = sdk_1.BigNum.zero(sdk_1.PRICE_PRECISION_EXP);
44
- const isClosingLong = (0, sdk_1.isVariant)(props.currentPositionDirection, 'long') &&
45
- (0, sdk_1.isVariant)(props.tradeDirection, 'short');
46
- const isClosingShort = (0, sdk_1.isVariant)(props.currentPositionDirection, 'short') &&
47
- (0, sdk_1.isVariant)(props.tradeDirection, 'long');
48
- if (!isClosingLong && !isClosingShort)
49
- return POTENTIAL_PROFIT_DEFAULT_STATE;
50
- if (!props.exitBaseSize)
51
- return POTENTIAL_PROFIT_DEFAULT_STATE;
52
- if (props.exitBaseSize.eqZero() ||
53
- props.currentPositionSize.lt(props.exitBaseSize)) {
54
- return POTENTIAL_PROFIT_DEFAULT_STATE;
55
- }
56
- const baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)
57
- ? props.exitBaseSize
58
- : props.currentPositionSize;
59
- // Notional size of amount being closed at entry and exit
60
- notionalSizeAtEntry = baseSizeBeingClosed.mul(props.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision));
61
- notionalSizeAtExit = baseSizeBeingClosed.mul(props.exitPrice.shiftTo(baseSizeBeingClosed.precision));
62
- if (isClosingLong) {
63
- estimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);
64
- }
65
- else if (isClosingShort) {
66
- estimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);
67
- }
68
- // subtract takerFee if applicable
69
- if (props.takerFeeBps > 0) {
70
- const takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));
71
- estimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);
72
- estimatedProfit = estimatedProfitBeforeFees.sub(estimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision));
73
- }
74
- else {
75
- estimatedProfit = estimatedProfitBeforeFees;
76
- }
77
- return {
78
- estimatedProfit,
79
- estimatedProfitBeforeFees,
80
- estimatedTakerFee,
81
- notionalSizeAtEntry,
82
- notionalSizeAtExit,
83
- };
84
- };
85
- /**
86
- * Check if the order type is a market order or oracle market order
87
- */
88
- const checkIsMarketOrderType = (orderType) => {
89
- return orderType === 'market' || orderType === 'oracle';
90
- };
91
- /**
92
- * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.
93
- * If the order type is limit order, a limit price must be provided.
94
- */
95
- const calculateLiquidationPriceAfterPerpTrade = ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision = 2, isEnteringHighLeverageMode, capLiqPrice, marginType, }) => {
96
- var _a, _b;
97
- const ALLOWED_ORDER_TYPES = [
98
- 'limit',
99
- 'market',
100
- 'oracle',
101
- 'stopMarket',
102
- 'stopLimit',
103
- 'oracleLimit',
104
- ];
105
- if (!ALLOWED_ORDER_TYPES.includes(orderType)) {
106
- console.error('Invalid order type for perp trade liquidation price calculation', orderType);
107
- return 0;
108
- }
109
- if (orderType === 'limit' && !limitPrice) {
110
- console.error('Limit order must have a limit price for perp trade liquidation price calculation');
111
- return 0;
112
- }
113
- const signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();
114
- const priceToUse = [
115
- 'limit',
116
- 'stopMarket',
117
- 'stopLimit',
118
- 'oracleLimit',
119
- ].includes(orderType)
120
- ? limitPrice
121
- : estEntryPrice;
122
- const liqPriceBn = userClient.liquidationPrice(perpMarketIndex, signedBaseSize, priceToUse, undefined, undefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation
123
- offsetCollateral, isEnteringHighLeverageMode, marginType === 'Isolated' ? 'Isolated' : undefined);
124
- if (liqPriceBn.isNeg()) {
125
- // means no liquidation price
126
- return 0;
127
- }
128
- // Check if user has a spot position using the same oracle as the perp market
129
- // If so, force capLiqPrice to be false to avoid incorrect price capping
130
- // Technically in this case, liq price could be lower for a short or higher for a long
131
- const perpMarketOracle = (_b = (_a = userClient.driftClient.getPerpMarketAccount(perpMarketIndex)) === null || _a === void 0 ? void 0 : _a.amm) === null || _b === void 0 ? void 0 : _b.oracle;
132
- const spotMarketWithSameOracle = userClient.driftClient
133
- .getSpotMarketAccounts()
134
- .find((market) => market.oracle.equals(perpMarketOracle));
135
- let hasSpotPositionWithSameOracle = false;
136
- if (spotMarketWithSameOracle) {
137
- const spotPosition = userClient.getSpotPosition(spotMarketWithSameOracle.marketIndex);
138
- hasSpotPositionWithSameOracle = !!spotPosition;
139
- }
140
- const effectiveCapLiqPrice = hasSpotPositionWithSameOracle
141
- ? false
142
- : capLiqPrice;
143
- const cappedLiqPriceBn = effectiveCapLiqPrice
144
- ? isLong
145
- ? sdk_1.BN.min(liqPriceBn, oraclePrice)
146
- : sdk_1.BN.max(liqPriceBn, oraclePrice)
147
- : liqPriceBn;
148
- const liqPriceBigNum = sdk_1.BigNum.from(cappedLiqPriceBn, sdk_1.PRICE_PRECISION_EXP);
149
- const liqPriceNum = Math.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;
150
- return liqPriceNum;
151
- };
152
- const convertLeverageToMarginRatio = (leverage) => {
153
- if (!leverage)
154
- return undefined;
155
- return Math.round((1 / leverage) * sdk_1.MARGIN_PRECISION.toNumber());
156
- };
157
- const convertMarginRatioToLeverage = (marginRatio, decimals) => {
158
- if (!marginRatio)
159
- return undefined;
160
- const leverage = 1 / (marginRatio / sdk_1.MARGIN_PRECISION.toNumber());
161
- return decimals
162
- ? parseFloat(leverage.toFixed(decimals))
163
- : Math.round(leverage);
164
- };
165
- const getMarketTickSize = (driftClient, marketId) => {
166
- const marketAccount = marketId.isPerp
167
- ? driftClient.getPerpMarketAccount(marketId.marketIndex)
168
- : driftClient.getSpotMarketAccount(marketId.marketIndex);
169
- if (!marketAccount)
170
- return sdk_1.ZERO;
171
- if (marketId.isPerp) {
172
- return marketAccount.amm.orderTickSize;
173
- }
174
- else {
175
- return marketAccount.orderTickSize;
176
- }
177
- };
178
- const getMarketTickSizeDecimals = (driftClient, marketId) => {
179
- const tickSize = getMarketTickSize(driftClient, marketId);
180
- const decimalPlaces = Math.max(0, Math.floor(Math.log10(sdk_1.PRICE_PRECISION.div(tickSize.eq(sdk_1.ZERO) ? sdk_1.ONE : tickSize).toNumber())));
181
- return decimalPlaces;
182
- };
183
- const getMarketStepSize = (driftClient, marketId) => {
184
- const marketAccount = marketId.isPerp
185
- ? driftClient.getPerpMarketAccount(marketId.marketIndex)
186
- : driftClient.getSpotMarketAccount(marketId.marketIndex);
187
- if (!marketAccount)
188
- return sdk_1.ZERO;
189
- if (marketId.isPerp) {
190
- return marketAccount.amm.orderStepSize;
191
- }
192
- else {
193
- return marketAccount.orderStepSize;
194
- }
195
- };
196
- const getMarketStepSizeDecimals = (driftClient, marketId) => {
197
- const stepSize = getMarketStepSize(driftClient, marketId);
198
- const decimalPlaces = Math.max(0, Math.floor(Math.log10(sdk_1.AMM_RESERVE_PRECISION.div(stepSize.eq(sdk_1.ZERO) ? sdk_1.ONE : stepSize).toNumber())));
199
- return decimalPlaces;
200
- };
201
- /**
202
- * Checks if a given order amount represents an entire position order
203
- * by comparing it with MAX_LEVERAGE_ORDER_SIZE
204
- * @param orderAmount - The BigNum order amount to check
205
- * @returns true if the order is for the entire position, false otherwise
206
- */
207
- const isEntirePositionOrder = (orderAmount) => {
208
- const maxLeverageSize = new sdk_1.BigNum(sdk_1.MAX_LEVERAGE_ORDER_SIZE, orderAmount.precision);
209
- const isMaxLeverage = Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;
210
- // Some order paths produce a truncated u64::MAX instead of MAX_LEVERAGE_ORDER_SIZE
211
- const ALTERNATIVE_MAX_ORDER_SIZE = '18446744072000000000';
212
- const alternativeMaxSize = new sdk_1.BigNum(ALTERNATIVE_MAX_ORDER_SIZE, orderAmount.precision);
213
- const isAlternativeMax = Math.abs(alternativeMaxSize.sub(orderAmount).toNum()) < 1;
214
- return isMaxLeverage || isAlternativeMax;
215
- };
216
- exports.isEntirePositionOrder = isEntirePositionOrder;
217
- /**
218
- * Gets the MAX_LEVERAGE_ORDER_SIZE as a BigNum with the same precision as the given amount
219
- * @param orderAmount - The BigNum order amount to match precision with
220
- * @returns BigNum representation of MAX_LEVERAGE_ORDER_SIZE
221
- */
222
- const getMaxLeverageOrderSize = (orderAmount) => {
223
- return new sdk_1.BigNum(sdk_1.MAX_LEVERAGE_ORDER_SIZE, orderAmount.precision);
224
- };
225
- exports.getMaxLeverageOrderSize = getMaxLeverageOrderSize;
226
- /**
227
- * Formats an order size for display, showing "Entire Position" if it's a max leverage order
228
- * @param orderAmount - The BigNum order amount to format
229
- * @param formatFn - Optional custom format function, defaults to prettyPrint()
230
- * @returns Formatted string showing either "Entire Position" or the formatted amount
231
- */
232
- const formatOrderSize = (orderAmount, formatFn) => {
233
- if ((0, exports.isEntirePositionOrder)(orderAmount)) {
234
- return 'Entire Position';
235
- }
236
- return formatFn ? formatFn(orderAmount) : orderAmount.prettyPrint();
237
- };
238
- exports.formatOrderSize = formatOrderSize;
239
- /**
240
- * Calculate the margin used for a specific perp position
241
- * Returns the minimum of user's total collateral or the position's weighted value
242
- */
243
- const getMarginUsedForPosition = (user, marketIndex, includeOpenOrders = true) => {
244
- const perpPosition = user.getPerpPosition(marketIndex);
245
- if (!perpPosition)
246
- return undefined;
247
- const hc = user.getPerpPositionHealth({
248
- marginCategory: 'Initial',
249
- perpPosition,
250
- includeOpenOrders,
251
- });
252
- const userCollateral = user.getTotalCollateral();
253
- return userCollateral.lt(hc.weightedValue)
254
- ? userCollateral
255
- : hc.weightedValue;
256
- };
257
- /**
258
- * Validate if a leverage change would exceed the user's free collateral
259
- * Returns true if the change is valid (doesn't exceed free collateral), false otherwise
260
- */
261
- const validateLeverageChange = ({ user, marketIndex, newLeverage, }) => {
262
- try {
263
- // Convert leverage to margin ratio
264
- const newMarginRatio = convertLeverageToMarginRatio(newLeverage);
265
- if (!newMarginRatio)
266
- return true;
267
- // Get the perp position from the user
268
- const perpPosition = user.getPerpPosition(marketIndex);
269
- if (!perpPosition)
270
- return true;
271
- // Get current position weighted value
272
- const currentPositionWeightedValue = user.getPerpPositionHealth({
273
- marginCategory: 'Initial',
274
- perpPosition,
275
- }).weightedValue;
276
- // Create a modified version of the position with new maxMarginRatio
277
- const modifiedPosition = {
278
- ...perpPosition,
279
- maxMarginRatio: newMarginRatio,
280
- };
281
- // Calculate new weighted value with the modified position
282
- const newPositionWeightedValue = user.getPerpPositionHealth({
283
- marginCategory: 'Initial',
284
- perpPosition: modifiedPosition,
285
- }).weightedValue;
286
- const perpPositionWeightedValueDelta = newPositionWeightedValue.sub(currentPositionWeightedValue);
287
- const freeCollateral = user.getFreeCollateral();
288
- // Check if weighted value delta exceeds free collateral
289
- return perpPositionWeightedValueDelta.lte(freeCollateral);
290
- }
291
- catch (error) {
292
- console.warn('Error validating leverage change:', error);
293
- return true; // Allow change if validation fails
294
- }
295
- };
296
- exports.TRADING_UTILS = {
297
- calculatePnlPctFromPosition,
298
- calculatePotentialProfit,
299
- calculateLiquidationPriceAfterPerpTrade,
300
- checkIsMarketOrderType,
301
- convertLeverageToMarginRatio,
302
- convertMarginRatioToLeverage,
303
- getMarketTickSize,
304
- getMarketTickSizeDecimals,
305
- getMarketStepSize,
306
- getMarketStepSizeDecimals,
307
- isEntirePositionOrder: exports.isEntirePositionOrder,
308
- getMaxLeverageOrderSize: exports.getMaxLeverageOrderSize,
309
- formatOrderSize: exports.formatOrderSize,
310
- getMarginUsedForPosition,
311
- validateLeverageChange,
312
- };
313
- //# sourceMappingURL=trading.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"trading.js","sourceRoot":"","sources":["../../src/common-ui-utils/trading.ts"],"names":[],"mappings":";;;AAAA,yCAiByB;AAGzB,MAAM,2BAA2B,GAAG,CACnC,GAAO,EACP,QAAsB,EACtB,UAAe,EACN,EAAE;;IACX,IAAI,CAAC,CAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAA,KAAI,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAC,EAAE,CAAC,UAAI,CAAC,CAAA;QACrE,OAAO,CAAC,CAAC;IAEV,IAAI,aAAqB,CAAC;IAE1B,IAAI,UAAU,EAAE,CAAC;QAChB,aAAa,GAAG,YAAM,CAAC,IAAI,CAAC,UAAU,EAAE,yBAAmB,CAAC,CAAC,KAAK,EAAE,CAAC;IACtE,CAAC;SAAM,CAAC;QACP,MAAM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A,aAAa,GAAG;IAC5B,2BAA2B;IAC3B,wBAAwB;IACxB,uCAAuC;IACvC,sBAAsB;IACtB,4BAA4B;IAC5B,4BAA4B;IAC5B,iBAAiB;IACjB,yBAAyB;IACzB,iBAAiB;IACjB,yBAAyB;IACzB,qBAAqB,EAArB,6BAAqB;IACrB,uBAAuB,EAAvB,+BAAuB;IACvB,eAAe,EAAf,uBAAe;IACf,wBAAwB;IACxB,sBAAsB;CACtB,CAAC","sourcesContent":["import {\n\tAMM_RESERVE_PRECISION,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMARGIN_PRECISION,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketAccount,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n\tUser,\n\tZERO,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { MarketId, OpenPosition, UIOrderType } from 'src/types';\n\nconst calculatePnlPctFromPosition = (\n\tpnl: BN,\n\tposition: OpenPosition,\n\tmarginUsed?: BN\n): number => {\n\tif (!position?.quoteEntryAmount || position?.quoteEntryAmount.eq(ZERO))\n\t\treturn 0;\n\n\tlet marginUsedNum: number;\n\n\tif (marginUsed) {\n\t\tmarginUsedNum = BigNum.from(marginUsed, QUOTE_PRECISION_EXP).toNum();\n\t} else {\n\t\tconst leverage = convertMarginRatioToLeverage(position.maxMarginRatio) ?? 1;\n\t\tconst quoteEntryAmountNum = BigNum.from(\n\t\t\tposition.quoteEntryAmount.abs(),\n\t\t\tQUOTE_PRECISION_EXP\n\t\t).toNum();\n\n\t\tif (leverage <= 0 || quoteEntryAmountNum <= 0) {\n\t\t\tmarginUsedNum = 0;\n\t\t} else {\n\t\t\tmarginUsedNum = quoteEntryAmountNum / leverage;\n\t\t}\n\t}\n\n\tif (marginUsedNum <= 0) {\n\t\treturn 0;\n\t}\n\n\treturn (\n\t\tBigNum.from(pnl, QUOTE_PRECISION_EXP)\n\t\t\t.shift(5)\n\t\t\t.div(BigNum.fromPrint(`${marginUsedNum}`, QUOTE_PRECISION_EXP))\n\t\t\t.toNum() * 100\n\t);\n};\n\nconst POTENTIAL_PROFIT_DEFAULT_STATE = {\n\testimatedProfit: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedProfitBeforeFees: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedTakerFee: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtEntry: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtExit: BigNum.zero(PRICE_PRECISION_EXP),\n};\n\nconst calculatePotentialProfit = (props: {\n\tcurrentPositionSize: BigNum;\n\tcurrentPositionDirection: PositionDirection;\n\tcurrentPositionEntryPrice: BigNum;\n\ttradeDirection: PositionDirection;\n\t/**\n\t * Amount of position being closed in base asset size\n\t */\n\texitBaseSize: BigNum;\n\t/**\n\t * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)\n\t */\n\texitPrice: BigNum;\n\ttakerFeeBps: number;\n\tslippageTolerance?: number;\n\tisMarketOrder?: boolean;\n}): {\n\testimatedProfit: BigNum;\n\testimatedProfitBeforeFees: BigNum;\n\testimatedTakerFee: BigNum;\n\tnotionalSizeAtEntry: BigNum;\n\tnotionalSizeAtExit: BigNum;\n} => {\n\tlet estimatedProfit = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedProfitBeforeFees = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedTakerFee = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtEntry = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtExit = BigNum.zero(PRICE_PRECISION_EXP);\n\n\tconst isClosingLong =\n\t\tisVariant(props.currentPositionDirection, 'long') &&\n\t\tisVariant(props.tradeDirection, 'short');\n\tconst isClosingShort =\n\t\tisVariant(props.currentPositionDirection, 'short') &&\n\t\tisVariant(props.tradeDirection, 'long');\n\n\tif (!isClosingLong && !isClosingShort) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\tif (!props.exitBaseSize) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\n\tif (\n\t\tprops.exitBaseSize.eqZero() ||\n\t\tprops.currentPositionSize.lt(props.exitBaseSize)\n\t) {\n\t\treturn POTENTIAL_PROFIT_DEFAULT_STATE;\n\t}\n\n\tconst baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)\n\t\t? props.exitBaseSize\n\t\t: props.currentPositionSize;\n\n\t// Notional size of amount being closed at entry and exit\n\tnotionalSizeAtEntry = baseSizeBeingClosed.mul(\n\t\tprops.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\tnotionalSizeAtExit = baseSizeBeingClosed.mul(\n\t\tprops.exitPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\n\tif (isClosingLong) {\n\t\testimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);\n\t} else if (isClosingShort) {\n\t\testimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);\n\t}\n\n\t// subtract takerFee if applicable\n\tif (props.takerFeeBps > 0) {\n\t\tconst takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));\n\t\testimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);\n\t\testimatedProfit = estimatedProfitBeforeFees.sub(\n\t\t\testimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision)\n\t\t);\n\t} else {\n\t\testimatedProfit = estimatedProfitBeforeFees;\n\t}\n\n\treturn {\n\t\testimatedProfit,\n\t\testimatedProfitBeforeFees,\n\t\testimatedTakerFee,\n\t\tnotionalSizeAtEntry,\n\t\tnotionalSizeAtExit,\n\t};\n};\n\n/**\n * Check if the order type is a market order or oracle market order\n */\nconst checkIsMarketOrderType = (orderType: UIOrderType) => {\n\treturn orderType === 'market' || orderType === 'oracle';\n};\n\n/**\n * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.\n * If the order type is limit order, a limit price must be provided.\n */\nconst calculateLiquidationPriceAfterPerpTrade = ({\n\testEntryPrice,\n\torderType,\n\tperpMarketIndex,\n\ttradeBaseSize,\n\tisLong,\n\tuserClient,\n\toraclePrice,\n\tlimitPrice,\n\toffsetCollateral,\n\tprecision = 2,\n\tisEnteringHighLeverageMode,\n\tcapLiqPrice,\n\tmarginType,\n}: {\n\testEntryPrice: BN;\n\torderType: UIOrderType;\n\tperpMarketIndex: number;\n\ttradeBaseSize: BN;\n\tisLong: boolean;\n\tuserClient: User;\n\toraclePrice: BN;\n\tlimitPrice?: BN;\n\toffsetCollateral?: BN;\n\tprecision?: number;\n\tisEnteringHighLeverageMode?: boolean;\n\tcapLiqPrice?: boolean;\n\tmarginType?: 'Cross' | 'Isolated';\n}) => {\n\tconst ALLOWED_ORDER_TYPES: UIOrderType[] = [\n\t\t'limit',\n\t\t'market',\n\t\t'oracle',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t];\n\n\tif (!ALLOWED_ORDER_TYPES.includes(orderType)) {\n\t\tconsole.error(\n\t\t\t'Invalid order type for perp trade liquidation price calculation',\n\t\t\torderType\n\t\t);\n\t\treturn 0;\n\t}\n\n\tif (orderType === 'limit' && !limitPrice) {\n\t\tconsole.error(\n\t\t\t'Limit order must have a limit price for perp trade liquidation price calculation'\n\t\t);\n\t\treturn 0;\n\t}\n\n\tconst signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();\n\tconst priceToUse = [\n\t\t'limit',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t].includes(orderType)\n\t\t? limitPrice\n\t\t: estEntryPrice;\n\n\tconst liqPriceBn = userClient.liquidationPrice(\n\t\tperpMarketIndex,\n\t\tsignedBaseSize,\n\t\tpriceToUse,\n\t\tundefined,\n\t\tundefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation\n\t\toffsetCollateral,\n\t\tisEnteringHighLeverageMode,\n\t\tmarginType === 'Isolated' ? 'Isolated' : undefined\n\t);\n\n\tif (liqPriceBn.isNeg()) {\n\t\t// means no liquidation price\n\t\treturn 0;\n\t}\n\n\t// Check if user has a spot position using the same oracle as the perp market\n\t// If so, force capLiqPrice to be false to avoid incorrect price capping\n\t// Technically in this case, liq price could be lower for a short or higher for a long\n\tconst perpMarketOracle =\n\t\tuserClient.driftClient.getPerpMarketAccount(perpMarketIndex)?.amm?.oracle;\n\n\tconst spotMarketWithSameOracle = userClient.driftClient\n\t\t.getSpotMarketAccounts()\n\t\t.find((market) => market.oracle.equals(perpMarketOracle));\n\n\tlet hasSpotPositionWithSameOracle = false;\n\tif (spotMarketWithSameOracle) {\n\t\tconst spotPosition = userClient.getSpotPosition(\n\t\t\tspotMarketWithSameOracle.marketIndex\n\t\t);\n\t\thasSpotPositionWithSameOracle = !!spotPosition;\n\t}\n\n\tconst effectiveCapLiqPrice = hasSpotPositionWithSameOracle\n\t\t? false\n\t\t: capLiqPrice;\n\n\tconst cappedLiqPriceBn = effectiveCapLiqPrice\n\t\t? isLong\n\t\t\t? BN.min(liqPriceBn, oraclePrice)\n\t\t\t: BN.max(liqPriceBn, oraclePrice)\n\t\t: liqPriceBn;\n\n\tconst liqPriceBigNum = BigNum.from(cappedLiqPriceBn, PRICE_PRECISION_EXP);\n\n\tconst liqPriceNum =\n\t\tMath.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;\n\n\treturn liqPriceNum;\n};\n\nconst convertLeverageToMarginRatio = (leverage: number): number | undefined => {\n\tif (!leverage) return undefined;\n\treturn Math.round((1 / leverage) * MARGIN_PRECISION.toNumber());\n};\n\nconst convertMarginRatioToLeverage = (\n\tmarginRatio: number,\n\tdecimals?: number\n): number | undefined => {\n\tif (!marginRatio) return undefined;\n\n\tconst leverage = 1 / (marginRatio / MARGIN_PRECISION.toNumber());\n\n\treturn decimals\n\t\t? parseFloat(leverage.toFixed(decimals))\n\t\t: Math.round(leverage);\n};\n\nconst getMarketTickSize = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n): BN => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderTickSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderTickSize;\n\t}\n};\n\nconst getMarketTickSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst tickSize = getMarketTickSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tPRICE_PRECISION.div(tickSize.eq(ZERO) ? ONE : tickSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\nconst getMarketStepSize = (driftClient: DriftClient, marketId: MarketId) => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderStepSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderStepSize;\n\t}\n};\n\nconst getMarketStepSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst stepSize = getMarketStepSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tAMM_RESERVE_PRECISION.div(stepSize.eq(ZERO) ? ONE : stepSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\n/**\n * Checks if a given order amount represents an entire position order\n * by comparing it with MAX_LEVERAGE_ORDER_SIZE\n * @param orderAmount - The BigNum order amount to check\n * @returns true if the order is for the entire position, false otherwise\n */\nexport const isEntirePositionOrder = (orderAmount: BigNum): boolean => {\n\tconst maxLeverageSize = new BigNum(\n\t\tMAX_LEVERAGE_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\n\tconst isMaxLeverage = Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;\n\n\t// Some order paths produce a truncated u64::MAX instead of MAX_LEVERAGE_ORDER_SIZE\n\tconst ALTERNATIVE_MAX_ORDER_SIZE = '18446744072000000000';\n\tconst alternativeMaxSize = new BigNum(\n\t\tALTERNATIVE_MAX_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\tconst isAlternativeMax =\n\t\tMath.abs(alternativeMaxSize.sub(orderAmount).toNum()) < 1;\n\n\treturn isMaxLeverage || isAlternativeMax;\n};\n\n/**\n * Gets the MAX_LEVERAGE_ORDER_SIZE as a BigNum with the same precision as the given amount\n * @param orderAmount - The BigNum order amount to match precision with\n * @returns BigNum representation of MAX_LEVERAGE_ORDER_SIZE\n */\nexport const getMaxLeverageOrderSize = (orderAmount: BigNum): BigNum => {\n\treturn new BigNum(MAX_LEVERAGE_ORDER_SIZE, orderAmount.precision);\n};\n\n/**\n * Formats an order size for display, showing \"Entire Position\" if it's a max leverage order\n * @param orderAmount - The BigNum order amount to format\n * @param formatFn - Optional custom format function, defaults to prettyPrint()\n * @returns Formatted string showing either \"Entire Position\" or the formatted amount\n */\nexport const formatOrderSize = (\n\torderAmount: BigNum,\n\tformatFn?: (amount: BigNum) => string\n): string => {\n\tif (isEntirePositionOrder(orderAmount)) {\n\t\treturn 'Entire Position';\n\t}\n\treturn formatFn ? formatFn(orderAmount) : orderAmount.prettyPrint();\n};\n\n/**\n * Calculate the margin used for a specific perp position\n * Returns the minimum of user's total collateral or the position's weighted value\n */\nconst getMarginUsedForPosition = (\n\tuser: User,\n\tmarketIndex: number,\n\tincludeOpenOrders = true\n): BN | undefined => {\n\tconst perpPosition = user.getPerpPosition(marketIndex);\n\tif (!perpPosition) return undefined;\n\n\tconst hc = user.getPerpPositionHealth({\n\t\tmarginCategory: 'Initial',\n\t\tperpPosition,\n\t\tincludeOpenOrders,\n\t});\n\tconst userCollateral = user.getTotalCollateral();\n\treturn userCollateral.lt(hc.weightedValue)\n\t\t? userCollateral\n\t\t: hc.weightedValue;\n};\n\n/**\n * Validate if a leverage change would exceed the user's free collateral\n * Returns true if the change is valid (doesn't exceed free collateral), false otherwise\n */\nconst validateLeverageChange = ({\n\tuser,\n\tmarketIndex,\n\tnewLeverage,\n}: {\n\tuser: User;\n\tmarketIndex: number;\n\tnewLeverage: number;\n}): boolean => {\n\ttry {\n\t\t// Convert leverage to margin ratio\n\t\tconst newMarginRatio = convertLeverageToMarginRatio(newLeverage);\n\t\tif (!newMarginRatio) return true;\n\n\t\t// Get the perp position from the user\n\t\tconst perpPosition = user.getPerpPosition(marketIndex);\n\t\tif (!perpPosition) return true;\n\n\t\t// Get current position weighted value\n\t\tconst currentPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition,\n\t\t}).weightedValue;\n\n\t\t// Create a modified version of the position with new maxMarginRatio\n\t\tconst modifiedPosition = {\n\t\t\t...perpPosition,\n\t\t\tmaxMarginRatio: newMarginRatio,\n\t\t};\n\n\t\t// Calculate new weighted value with the modified position\n\t\tconst newPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition: modifiedPosition,\n\t\t}).weightedValue;\n\n\t\tconst perpPositionWeightedValueDelta = newPositionWeightedValue.sub(\n\t\t\tcurrentPositionWeightedValue\n\t\t);\n\n\t\tconst freeCollateral = user.getFreeCollateral();\n\n\t\t// Check if weighted value delta exceeds free collateral\n\t\treturn perpPositionWeightedValueDelta.lte(freeCollateral);\n\t} catch (error) {\n\t\tconsole.warn('Error validating leverage change:', error);\n\t\treturn true; // Allow change if validation fails\n\t}\n};\n\nexport const TRADING_UTILS = {\n\tcalculatePnlPctFromPosition,\n\tcalculatePotentialProfit,\n\tcalculateLiquidationPriceAfterPerpTrade,\n\tcheckIsMarketOrderType,\n\tconvertLeverageToMarginRatio,\n\tconvertMarginRatioToLeverage,\n\tgetMarketTickSize,\n\tgetMarketTickSizeDecimals,\n\tgetMarketStepSize,\n\tgetMarketStepSizeDecimals,\n\tisEntirePositionOrder,\n\tgetMaxLeverageOrderSize,\n\tformatOrderSize,\n\tgetMarginUsedForPosition,\n\tvalidateLeverageChange,\n};\n"]}
@@ -1,18 +0,0 @@
1
- import { BN, DriftClient, PerpMarketConfig, PerpPosition, PublicKey, User } from '@drift-labs/sdk';
2
- import { OpenPosition } from '../types';
3
- export declare const USER_UTILS: {
4
- getOpenPositionData: (driftClient: DriftClient, userPositions: PerpPosition[], user: User, perpMarketLookup: PerpMarketConfig[], markPriceCallback?: (marketIndex: number) => BN) => OpenPosition[];
5
- checkIfUserAccountExists: (driftClient: DriftClient, config: {
6
- type: 'userPubKey';
7
- userPubKey: PublicKey;
8
- } | {
9
- type: 'subAccountId';
10
- subAccountId: number;
11
- authority: PublicKey;
12
- }) => Promise<boolean>;
13
- getUserMaxLeverageForMarket: (user: User | undefined, marketIndex: number, marketLeverageDetails: {
14
- regularMaxLeverage: number;
15
- highLeverageMaxLeverage: number;
16
- hasHighLeverage: boolean;
17
- }, uiSavedMaxLeverage?: number) => number;
18
- };
@@ -1 +0,0 @@
1
- {"version":3,"file":"user.js","sourceRoot":"","sources":["../../src/common-ui-utils/user.ts"],"names":[],"mappings":";;;AAAA,yCA0ByB;AACzB,oCAAkD;AAClD,uCAA0C;AAC1C,oCAAsC;AAEtC,MAAM,mBAAmB,GAAG,CAC3B,WAAwB,EACxB,aAA6B,EAC7B,IAAU,EACV,gBAAoC,EACpC,iBAA+C,EAC9B,EAAE;IACnB,MAAM,gBAAgB,GAAG,WAAW,CAAC,eAAe,EAAE,CAAC,gBAAgB,CAAC;IAExE,MAAM,SAAS,GAAmB,aAA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,EAAE,CAAC,UAAI,CAAC,CAAC;IACtE,MAAM,eAAe,GAAG,oBAAoB,CAAC,UAAU,KAAK,CAAC,CAAC;IAE9D,IAAI,4BAA4B,EAAE,CAAC;QAClC,+EAA+E;QAC/E,IAAI,cAAc,IAAI,eAAe,IAAI,kBAAkB,EAAE,CAAC;YAC7D,OAAO,kBAAkB,CAAC;QAC3B,CAAC;QAED,OAAO,UAAU,CAChB,CAAC,CAAC,CAAC,GAAG,oBAAoB,CAAC,cAAc,CAAC,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAC9D,CAAC;IACH,CAAC;IAED,IAAI,cAAc,EAAE,CAAC;QACpB,sGAAsG;QACtG,iEAAiE;QACjE,MAAM,wBAAwB,GAAG,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;QACpE,MAAM,mBAAmB,GAAG,wBAAwB;YACnD,CAAC,CAAC,qBAAqB,CAAC,eAAe;gBACtC,CAAC,CAAC,qBAAqB,CAAC,uBAAuB;gBAC/C,CAAC,CAAC,qBAAqB,CAAC,kBAAkB;YAC3C,CAAC,CAAC,qBAAqB,CAAC,kBAAkB,CAAC;QAC5C,OAAO,mBAAmB,CAAC;IAC5B,CAAC;IAED,0EAA0E;IAC1E,OAAO,oBAAoB,CAAC;AAC7B,CAAC,CAAC;AAEW,QAAA,UAAU,GAAG;IACzB,mBAAmB;IACnB,wBAAwB;IACxB,2BAA2B;CAC3B,CAAC","sourcesContent":["import {\n\tBASE_PRECISION_EXP,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMarketStatus,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketConfig,\n\tPerpPosition,\n\tPositionDirection,\n\tPublicKey,\n\tQUOTE_PRECISION_EXP,\n\tQUOTE_SPOT_MARKET_INDEX,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateCostBasis,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tgetUserAccountPublicKeySync,\n\tcalculateUnsettledFundingPnl,\n\tisOracleValid,\n\tAMM_RESERVE_PRECISION,\n} from '@drift-labs/sdk';\nimport { OpenPosition, UIMarket } from '../types';\nimport { TRADING_UTILS } from './trading';\nimport { ENUM_UTILS } from '../utils';\n\nconst getOpenPositionData = (\n\tdriftClient: DriftClient,\n\tuserPositions: PerpPosition[],\n\tuser: User,\n\tperpMarketLookup: PerpMarketConfig[],\n\tmarkPriceCallback?: (marketIndex: number) => BN\n): OpenPosition[] => {\n\tconst oracleGuardRails = driftClient.getStateAccount().oracleGuardRails;\n\n\tconst newResult: OpenPosition[] = userPositions\n\t\t.filter(\n\t\t\t(position) =>\n\t\t\t\t!position.baseAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.quoteAssetAmount.eq(ZERO)\n\t\t)\n\t\t.map((position) => {\n\t\t\tconst perpMarketConfig = perpMarketLookup[position.marketIndex];\n\t\t\tconst perpMarket = driftClient.getPerpMarketAccount(position.marketIndex);\n\n\t\t\tconst usdcSpotMarket = driftClient.getSpotMarketAccount(\n\t\t\t\tQUOTE_SPOT_MARKET_INDEX\n\t\t\t);\n\n\t\t\tconst oraclePriceData = driftClient.getOracleDataForPerpMarket(\n\t\t\t\tposition.marketIndex\n\t\t\t);\n\n\t\t\tlet oraclePrice = oraclePriceData.price;\n\n\t\t\t// mark price fetched with a callback so we don't need extra dlob server calls. fallback to oracle\n\t\t\tlet markPrice = markPriceCallback\n\t\t\t\t? markPriceCallback(position.marketIndex) ?? oraclePriceData.price\n\t\t\t\t: oraclePriceData.price;\n\n\t\t\tlet estExitPrice = user.getPositionEstimatedExitPriceAndPnl(\n\t\t\t\tposition,\n\t\t\t\tposition.baseAssetAmount\n\t\t\t)[0];\n\n\t\t\tconst entryPrice = calculateEntryPrice(position);\n\n\t\t\tconst isShort = position.baseAssetAmount.isNeg();\n\n\t\t\tif (UIMarket.checkIsPredictionMarket(perpMarketConfig)) {\n\t\t\t\tconst isResolved =\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.SETTLEMENT) ||\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.DELISTED);\n\n\t\t\t\tif (isResolved) {\n\t\t\t\t\tconst resolvedToNo = perpMarket.expiryPrice.lte(\n\t\t\t\t\t\tZERO.add(perpMarket.amm.orderTickSize)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst price = resolvedToNo\n\t\t\t\t\t\t? ZERO.mul(PRICE_PRECISION)\n\t\t\t\t\t\t: ONE.mul(PRICE_PRECISION);\n\n\t\t\t\t\testExitPrice = price;\n\t\t\t\t\tmarkPrice = price;\n\t\t\t\t\toraclePrice = price;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if for any reason oracle or mark price blips to 0, fallback to the other one so we don't show a crazy pnl\n\t\t\tif (markPrice.lte(ZERO) && oraclePrice.gt(ZERO)) {\n\t\t\t\tmarkPrice = oraclePrice;\n\t\t\t}\n\n\t\t\tif (oraclePrice.lte(ZERO) && markPrice.gt(ZERO)) {\n\t\t\t\toraclePrice = markPrice;\n\t\t\t}\n\n\t\t\tconst pnlVsMark = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(markPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\tconst pnlVsOracle = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(oraclePrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\treturn {\n\t\t\t\tmarketIndex: position.marketIndex,\n\t\t\t\tmarketSymbol: perpMarketConfig.symbol,\n\t\t\t\tdirection: isShort ? 'short' : 'long',\n\t\t\t\tnotional: position.baseAssetAmount\n\t\t\t\t\t.abs()\n\t\t\t\t\t.mul(markPrice)\n\t\t\t\t\t.div(AMM_RESERVE_PRECISION),\n\t\t\t\tbaseSize: position.baseAssetAmount,\n\t\t\t\tmarkPrice,\n\t\t\t\tentryPrice,\n\t\t\t\texitPrice: estExitPrice,\n\t\t\t\tliqPrice: user.isPerpPositionIsolated(position)\n\t\t\t\t\t? user.liquidationPrice(\n\t\t\t\t\t\t\tposition.marketIndex,\n\t\t\t\t\t\t\tZERO,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t'Isolated'\n\t\t\t\t\t )\n\t\t\t\t\t: user.liquidationPrice(position.marketIndex, ZERO),\n\t\t\t\tquoteAssetNotionalAmount: position.quoteAssetAmount,\n\t\t\t\tquoteEntryAmount: position.quoteEntryAmount,\n\t\t\t\tquoteBreakEvenAmount: position.quoteBreakEvenAmount,\n\t\t\t\tpnlVsMark,\n\t\t\t\tpnlVsOracle,\n\t\t\t\tunsettledPnl: calculateClaimablePnl(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tusdcSpotMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunsettledFundingPnl: calculateUnsettledFundingPnl(perpMarket, position),\n\t\t\t\t// Includes both settled and unsettled funding as well as fees\n\t\t\t\tfeesAndFundingPnl: calculateFeesAndFundingPnl(perpMarket, position),\n\t\t\t\ttotalUnrealizedPnl: calculatePositionPNL(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\ttrue,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunrealizedFundingPnl: user.getUnrealizedFundingPNL(\n\t\t\t\t\tposition.marketIndex\n\t\t\t\t),\n\t\t\t\tlastCumulativeFundingRate: position.lastCumulativeFundingRate,\n\t\t\t\topenOrders: position.openOrders,\n\t\t\t\tcostBasis: calculateCostBasis(position),\n\t\t\t\trealizedPnl: position.settledPnl,\n\t\t\t\tpnlIsClaimable: isOracleValid(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\toraclePriceData,\n\t\t\t\t\toracleGuardRails,\n\t\t\t\t\tperpMarket.amm.lastUpdateSlot?.toNumber()\n\t\t\t\t),\n\t\t\t\tmaxMarginRatio: position.maxMarginRatio,\n\t\t\t};\n\t\t});\n\n\treturn newResult;\n};\n\nconst checkIfUserAccountExists = async (\n\tdriftClient: DriftClient,\n\tconfig:\n\t\t| {\n\t\t\t\ttype: 'userPubKey';\n\t\t\t\tuserPubKey: PublicKey;\n\t\t }\n\t\t| {\n\t\t\t\ttype: 'subAccountId';\n\t\t\t\tsubAccountId: number;\n\t\t\t\tauthority: PublicKey;\n\t\t }\n) => {\n\tlet userPubKey: PublicKey;\n\n\tif (config.type === 'userPubKey') {\n\t\tuserPubKey = config.userPubKey;\n\t} else {\n\t\tuserPubKey = getUserAccountPublicKeySync(\n\t\t\tdriftClient.program.programId,\n\t\t\tconfig.authority,\n\t\t\tconfig.subAccountId\n\t\t);\n\t}\n\n\tconst accountInfo = await driftClient.connection.getAccountInfo(userPubKey);\n\n\treturn accountInfo !== null;\n};\n\n/**\n * A user's max leverage for a market is stored on-chain in the `PerpPosition` struct of the `UserAccount`.\n * There are a few scenarios for how a market's max leverage is defined:\n *\n * 1. When the user does not have a position (\"empty\" or not) in the market in their `UserAccount` data,\n * and creates an order for the market, an \"empty\" `PerpPosition` will be upsert to the `UserAccount` data,\n * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up\n * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be\n * \"empty\" if the user does not have the max 8 perp positions open. The max leverage is then derived from\n * the max margin ratio set in the `PerpPosition` struct.\n *\n * 2. If the user has a position (\"empty\" or not), but no open orders and is provided with a saved max leverage,\n * the saved max leverage is used.\n *\n * 3. When the user does not have a position (\"empty\" or not), it is expected of the UI to store and persist\n * the max leverage in the UI client.\n *\n * 4. In cases where the user has a position before the market max leverage feature was shipped, the\n * position is not expected to have a max margin ratio set, and the UI should display the regular max\n * leverage for the market, unless the user is already in High Leverage Mode, in which case the UI should\n * display the high leverage max leverage for the market (if any).\n */\nconst getUserMaxLeverageForMarket = (\n\tuser: User | undefined,\n\tmarketIndex: number,\n\tmarketLeverageDetails: {\n\t\tregularMaxLeverage: number;\n\t\thighLeverageMaxLeverage: number;\n\t\thasHighLeverage: boolean;\n\t},\n\tuiSavedMaxLeverage?: number\n) => {\n\t// if no saved max leverage is provided, return the regular max leverage for the market\n\tconst DEFAULT_MAX_LEVERAGE =\n\t\tuiSavedMaxLeverage ?? marketLeverageDetails.regularMaxLeverage;\n\n\tif (!user) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst openOrClosedPosition = user.getPerpPosition(marketIndex); // this position does not have to be open, it can be a closed position (a.k.a \"empty\") but has max margin ratio set.\n\n\tif (!openOrClosedPosition) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst positionHasMaxMarginRatioSet = !!openOrClosedPosition.maxMarginRatio;\n\tconst isPositionOpen = !openOrClosedPosition.baseAssetAmount.eq(ZERO);\n\tconst hasNoOpenOrders = openOrClosedPosition.openOrders === 0;\n\n\tif (positionHasMaxMarginRatioSet) {\n\t\t// Special case: open position with no orders - use UI saved value if available\n\t\tif (isPositionOpen && hasNoOpenOrders && uiSavedMaxLeverage) {\n\t\t\treturn uiSavedMaxLeverage;\n\t\t}\n\n\t\treturn parseFloat(\n\t\t\t((1 / openOrClosedPosition.maxMarginRatio) * 10000).toFixed(2)\n\t\t);\n\t}\n\n\tif (isPositionOpen) {\n\t\t// user has an existing position from before PML ship (this means no max margin ratio set onchain yet)\n\t\t// display max leverage for the leverage mode their account is in\n\t\tconst isUserInHighLeverageMode = user.isHighLeverageMode('Initial');\n\t\tconst grandfatheredMaxLev = isUserInHighLeverageMode\n\t\t\t? marketLeverageDetails.hasHighLeverage\n\t\t\t\t? marketLeverageDetails.highLeverageMaxLeverage\n\t\t\t\t: marketLeverageDetails.regularMaxLeverage\n\t\t\t: marketLeverageDetails.regularMaxLeverage;\n\t\treturn grandfatheredMaxLev;\n\t}\n\n\t// user has closed position with no margin ratio set, return default value\n\treturn DEFAULT_MAX_LEVERAGE;\n};\n\nexport const USER_UTILS = {\n\tgetOpenPositionData,\n\tcheckIfUserAccountExists,\n\tgetUserMaxLeverageForMarket,\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"WalletConnectionState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;IACzC,CAAC;CACD;AA9ED,sDA8EC","sourcesContent":["import { PublicKey } from '@drift-labs/sdk';\n\nexport enum ConnectionStateSteps {\n\tNotConnected = 0,\n\tAdapterConnected = 1,\n\tClientConnected = 2,\n\tBalanceLoaded = 4,\n\tSubaccountsSubscribed = 8,\n}\n\nexport enum ConnectionStates {\n\tNotConnected = ConnectionStateSteps.NotConnected,\n\tAdapterConnected = ConnectionStateSteps.AdapterConnected,\n\tClientConnected = ConnectionStateSteps.ClientConnected,\n\tBalanceLoaded = ConnectionStateSteps.BalanceLoaded,\n\tSubaccountsSubscribed = ConnectionStateSteps.SubaccountsSubscribed,\n\tFullyConnected = ConnectionStateSteps.AdapterConnected +\n\t\tConnectionStateSteps.ClientConnected +\n\t\tConnectionStateSteps.BalanceLoaded +\n\t\tConnectionStateSteps.SubaccountsSubscribed,\n}\n\nexport type ConnectionStepString = keyof typeof ConnectionStateSteps;\n\nexport type ConnectionStateString = keyof typeof ConnectionStates;\n\nexport class WalletConnectionState {\n\tstate: number;\n\tauthority: PublicKey;\n\n\tconstructor(authority: PublicKey) {\n\t\tthis.state = ConnectionStates.NotConnected;\n\t\tthis.authority = authority;\n\t}\n\n\tis(stateQuery: ConnectionStateString) {\n\t\tswitch (stateQuery) {\n\t\t\tcase 'NotConnected':\n\t\t\t\treturn this.state === ConnectionStates.NotConnected;\n\t\t\tcase 'AdapterConnected':\n\t\t\t\treturn (\n\t\t\t\t\t(this.state & ConnectionStates.AdapterConnected) ===\n\t\t\t\t\tConnectionStates.AdapterConnected\n\t\t\t\t);\n\t\t\tcase 'ClientConnected':\n\t\t\t\treturn (\n\t\t\t\t\t(this.state & ConnectionStates.ClientConnected) ===\n\t\t\t\t\tConnectionStates.ClientConnected\n\t\t\t\t);\n\t\t\tcase 'BalanceLoaded':\n\t\t\t\treturn (\n\t\t\t\t\t(this.state & ConnectionStates.BalanceLoaded) ===\n\t\t\t\t\tConnectionStates.BalanceLoaded\n\t\t\t\t);\n\t\t\tcase 'FullyConnected':\n\t\t\t\treturn (\n\t\t\t\t\t(this.state & ConnectionStates.FullyConnected) ===\n\t\t\t\t\tConnectionStates.FullyConnected\n\t\t\t\t);\n\t\t\tcase 'SubaccountsSubscribed':\n\t\t\t\treturn (\n\t\t\t\t\t(this.state & ConnectionStates.SubaccountsSubscribed) ===\n\t\t\t\t\tConnectionStates.SubaccountsSubscribed\n\t\t\t\t);\n\t\t\tdefault: {\n\t\t\t\t// Throw a typescript error if we have an unhandled case\n\t\t\t\tconst nothing: never = stateQuery;\n\t\t\t\treturn nothing;\n\t\t\t}\n\t\t}\n\t}\n\n\tupdate(updateStep: ConnectionStepString, authorityGate?: PublicKey) {\n\t\t// Check that authorities match before updating state\n\t\tif (authorityGate && !this.authority.equals(authorityGate)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (updateStep === 'NotConnected') {\n\t\t\tthis.state = ConnectionStates.NotConnected;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.state = this.state | ConnectionStateSteps[updateStep];\n\t}\n\n\tget NotConnected() {\n\t\treturn this.is('NotConnected');\n\t}\n\tget AdapterConnected() {\n\t\treturn this.is('AdapterConnected');\n\t}\n\tget ClientConnected() {\n\t\treturn this.is('ClientConnected');\n\t}\n\tget BalanceLoaded() {\n\t\treturn this.is('BalanceLoaded');\n\t}\n\tget FullyConnected() {\n\t\treturn this.is('FullyConnected');\n\t}\n\tget SubaccountsSubscribed() {\n\t\treturn this.is('SubaccountsSubscribed');\n\t}\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"enum.js","sourceRoot":"","sources":["../../src/utils/enum.ts"],"names":[],"mappings":";;;AAAO,MAAM,SAAS,GAAG,CAAC,KAAU,EAAE,KAAK,EAAE,EAAE;IAC9C,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACxD,CAAC,CAAC;AAFW,QAAA,SAAS,aAEpB;AAEF,SAAS,SAAS,CAAC,OAAe;IACjC,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAE/B,OAAO;QACN,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,EAAE,EAAE;KACnB,CAAC;AACH,CAAC;AAED,SAAS,SAAS,CAAC,OAA4B;;IAC9C,OAAO,MAAA,MAAM,CAAC,IAAI,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,EAAE,CAAC,0CAAG,CAAC,CAAC,CAAC;AACxC,CAAC;AAEY,QAAA,UAAU,GAAG;IACzB,KAAK,EAAE,iBAAS;IAChB,KAAK,EAAE,SAAS;IAChB,KAAK,EAAE,SAAS;CAChB,CAAC","sourcesContent":["export const matchEnum = (enum1: any, enum2) => {\n\treturn JSON.stringify(enum1) === JSON.stringify(enum2);\n};\n\nfunction enumToObj(enumStr: string) {\n\tif (!enumStr) return undefined;\n\n\treturn {\n\t\t[enumStr ?? '']: {},\n\t};\n}\n\nfunction enumToStr(enumStr: Record<string, any>) {\n\treturn Object.keys(enumStr ?? {})?.[0];\n}\n\nexport const ENUM_UTILS = {\n\tmatch: matchEnum,\n\ttoObj: enumToObj,\n\ttoStr: enumToStr,\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"equalityChecks.js","sourceRoot":"","sources":["../../src/utils/equalityChecks.ts"],"names":[],"mappings":";;;AAAA,wBAA+B;AAgB/B,MAAM,kBAAkB,GAAG,CAC1B,IAAS,EACT,IAAS,EACT,UAAkC,EACjC,EAAE;IACH,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,EAAE;;QACpC,MAAM,YAAY,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QACjC,MAAM,YAAY,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QACjC,MAAM,gBAAgB,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QAErC,QAAQ,YAAY,EAAE,CAAC;YACtB,KAAK,WAAW;gBACf,OAAO,IAA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 'primitiveArray'\n\t| 'bn'\n\t| 'bignum'\n\t| 'programEnum'\n\t| 'custom';\nexport type PropertyAndType<KeyOfObject> = [\n\tproperty: KeyOfObject,\n\ttype: PropertyType,\n\tcustomEqualityFn?: (a: any, b: any) => boolean\n];\n\nconst arePropertiesEqual = (\n\tobj1: any,\n\tobj2: any,\n\tproperties: PropertyAndType<any>[]\n) => {\n\treturn properties.every((property) => {\n\t\tconst propertyName = property[0];\n\t\tconst propertyType = property[1];\n\t\tconst customEqualityFn = property[2];\n\n\t\tswitch (propertyType) {\n\t\t\tcase 'primitive':\n\t\t\t\treturn obj1[propertyName] === obj2[propertyName];\n\t\t\tcase 'primitiveArray':\n\t\t\t\treturn (\n\t\t\t\t\tobj1[propertyName]?.length === obj2[propertyName]?.length &&\n\t\t\t\t\tobj1[propertyName]?.every((value: any, index: number) => {\n\t\t\t\t\t\treturn value === obj2[propertyName]?.[index];\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\tcase 'bn':\n\t\t\tcase 'bignum':\n\t\t\t\treturn obj1[propertyName]?.eq(obj2[propertyName]);\n\t\t\tcase 'programEnum':\n\t\t\t\treturn ENUM_UTILS.match(obj1[propertyName], obj2[propertyName]);\n\t\t\tcase 'custom':\n\t\t\t\tif (!customEqualityFn)\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'You need to provide a custom equality function for this property'\n\t\t\t\t\t);\n\n\t\t\t\treturn customEqualityFn(obj1[propertyName], obj2[propertyName]);\n\t\t\tdefault:\n\t\t\t\tthrow new Error('Invalid property type');\n\t\t}\n\t});\n};\n\nconst areTwoOpenPositionsEqual = (\n\topenPosition1: OpenPosition,\n\topenPosition2: OpenPosition\n) => {\n\tconst propertiesToCompare: PropertyAndType<keyof OpenPosition>[] = [\n\t\t['marketIndex', 'primitive'],\n\t\t['marketSymbol', 'primitive'],\n\t\t['direction', 'primitive'],\n\t\t['notional', 'bn'],\n\t\t['baseSize', 'bn'],\n\t\t['entryPrice', 'bn'],\n\t\t['exitPrice', 'bn'],\n\t\t['liqPrice', 'bn'],\n\t\t['pnlVsOracle', 'bn'],\n\t\t['pnlVsMark', 'bn'],\n\t\t['quoteAssetNotionalAmount', 'bn'],\n\t\t['quoteEntryAmount', 'bn'],\n\t\t['unrealizedFundingPnl', 'bn'],\n\t\t['lastCumulativeFundingRate', 'bn'],\n\t\t['openOrders', 'primitive'],\n\t\t['unsettledPnl', 'bn'],\n\t\t['unsettledFundingPnl', 'bn'],\n\t\t['totalUnrealizedPnl', 'bn'],\n\t\t['costBasis', 'bn'],\n\t\t['pnlIsClaimable', 'primitive'],\n\t\t['realizedPnl', 'bn'],\n\t];\n\n\treturn arePropertiesEqual(openPosition1, openPosition2, propertiesToCompare);\n};\n\nconst areOpenPositionListsEqual = (\n\topenPositions1: OpenPosition[],\n\topenPositions2: OpenPosition[]\n) => {\n\tif (openPositions1.length !== openPositions2.length) return false;\n\n\treturn openPositions1.every((openPosition, index) =>\n\t\tareTwoOpenPositionsEqual(openPosition, openPositions2[index])\n\t);\n};\n\nexport const EQUALITY_CHECKS = {\n\tarePropertiesEqual,\n\topenPosition: areTwoOpenPositionsEqual,\n\topenPositionLists: areOpenPositionListsEqual,\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAO,MAAM,iBAAiB,GAAG,CAChC,MAA0C,EACjC,EAAE;IACX,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;SAC3B,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC;SAC3C,GAAG,CACH,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAChB,GAAG,kBAAkB,CAAC,GAAG,CAAC,IAAI,kBAAkB,CAAC,KAAM,CAAC,EAAE,CAC3D;SACA,IAAI,CAAC,GAAG,CAAC,CAAC;AACb,CAAC,CAAC;AAVW,QAAA,iBAAiB,qBAU5B","sourcesContent":["export const encodeQueryParams = (\n\tparams: Record<string, string | undefined>\n): string => {\n\treturn Object.entries(params)\n\t\t.filter(([_, value]) => value !== undefined)\n\t\t.map(\n\t\t\t([key, value]) =>\n\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value!)}`\n\t\t)\n\t\t.join('&');\n};\n"]}
@@ -1,31 +0,0 @@
1
- import { BigNum, L2OrderBook } from '@drift-labs/sdk';
2
- export declare const TRADE_PRECISION = 6;
3
- export declare const getPctCompletion: (start: number, end: number, current: number) => number;
4
- export declare const sortBnAsc: (bnA: BN, bnB: BN) => 0 | 1 | -1;
5
- export declare const sortBnDesc: (bnA: BN, bnB: BN) => 0 | 1 | -1;
6
- export declare const getBigNumRoundedToStepSize: (baseSize: BigNum, stepSize: BN) => BigNum;
7
- export declare const truncateInputToPrecision: (input: string, marketPrecisionExp: BN) => string;
8
- export declare const roundToStepSize: (value: string, stepSize?: number) => string;
9
- export declare const roundToStepSizeIfLargeEnough: (value: string, stepSize?: number) => string;
10
- export declare const valueIsBelowStepSize: (value: string, stepSize: number) => boolean;
11
- /**
12
- * NOTE: Do not use modulo alone to check if numbers fit evenly.
13
- * Due to floating point precision issues this can return incorrect results.
14
- * i.e. 5.1 % 0.1 = 0.09999999999999959 (should be 0)
15
- * tells me 5.1 / 0.1 = 50.99999999999999
16
- */
17
- export declare const numbersFitEvenly: (numberOne: number, numberTwo: number) => boolean;
18
- export declare function roundToDecimal(value: number, decimals: number | undefined | null): number;
19
- export declare const roundBigNumToDecimalPlace: (bignum: BigNum, decimalPlaces: number) => BigNum;
20
- export declare const sortRecordsByTs: <T extends {
21
- ts: BN;
22
- }[]>(records: T | undefined, direction?: 'asc' | 'desc') => T[number][];
23
- export declare const COMMON_MATH: {
24
- calculateSpreadBidAskMark: (l2: Pick<L2OrderBook, 'bids' | 'asks'>, oraclePrice?: BN) => {
25
- bestBidPrice: BN;
26
- bestAskPrice: BN;
27
- markPrice: BN;
28
- spreadPct: any;
29
- spreadQuote: any;
30
- };
31
- };