@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
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getUIOrderRecordsLaterThanTarget = exports.getLatestOfTwoOrderRecords = exports.getLatestOfTwoUIOrderRecords = exports.sortOrderRecords = exports.sortUIOrderRecords = exports.sortUIOrderActionRecords = exports.sortUIMatchedOrderRecordAndAction = exports.getSortScoreForOrderActionRecords = exports.getSortScoreForOrderRecords = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const enum_1 = require("../enum");
6
+ const getChronologicalValueForOrderAction = (action) => {
7
+ return (0, enum_1.matchEnum)(action, sdk_1.OrderAction.PLACE)
8
+ ? 0
9
+ : (0, enum_1.matchEnum)(action, sdk_1.OrderAction.FILL)
10
+ ? 1
11
+ : 2;
12
+ };
13
+ /**
14
+ * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal
15
+ * @param orderA
16
+ * @param orderB
17
+ * @returns
18
+ */
19
+ const getSortScoreForOrderRecords = (orderA, orderB) => {
20
+ if (orderA.slot !== orderB.slot) {
21
+ return orderA.slot > orderB.slot ? 1 : -1;
22
+ }
23
+ return 0;
24
+ };
25
+ exports.getSortScoreForOrderRecords = getSortScoreForOrderRecords;
26
+ /**
27
+ * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal
28
+ * @param orderA
29
+ * @param orderB
30
+ * @returns
31
+ */
32
+ const getSortScoreForOrderActionRecords = (orderA, orderB) => {
33
+ if (orderA.slot !== orderB.slot) {
34
+ return orderA.slot > orderB.slot ? 1 : -1;
35
+ }
36
+ if (!(0, enum_1.matchEnum)(orderA.action, orderB.action)) {
37
+ // @ts-ignore
38
+ const orderAActionVal = getChronologicalValueForOrderAction(orderA.action);
39
+ // @ts-ignore
40
+ const orderBActionVal = getChronologicalValueForOrderAction(orderB.action);
41
+ return orderAActionVal > orderBActionVal ? 1 : -1;
42
+ }
43
+ // @ts-ignore
44
+ if (orderA.fillRecordId && orderB.fillRecordId) {
45
+ if (!orderA.fillRecordId.eq(orderB.fillRecordId)) {
46
+ // @ts-ignore
47
+ return orderA.fillRecordId.gt(orderB.fillRecordId) ? 1 : -1;
48
+ }
49
+ }
50
+ return 0;
51
+ };
52
+ exports.getSortScoreForOrderActionRecords = getSortScoreForOrderActionRecords;
53
+ const sortUIMatchedOrderRecordAndAction = (records, direction = 'desc') => {
54
+ const ascSortedRecords = records.sort((a, b) => (0, exports.getSortScoreForOrderActionRecords)(a.actionRecord, b.actionRecord));
55
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
56
+ };
57
+ exports.sortUIMatchedOrderRecordAndAction = sortUIMatchedOrderRecordAndAction;
58
+ const sortUIOrderActionRecords = (records, direction = 'desc') => {
59
+ const ascSortedRecords = records.sort(exports.getSortScoreForOrderActionRecords);
60
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
61
+ };
62
+ exports.sortUIOrderActionRecords = sortUIOrderActionRecords;
63
+ const sortUIOrderRecords = (records, direction = 'desc') => {
64
+ const ascSortedRecords = records.sort(exports.getSortScoreForOrderRecords);
65
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
66
+ };
67
+ exports.sortUIOrderRecords = sortUIOrderRecords;
68
+ const sortOrderRecords = (records, direction = 'desc') => {
69
+ const ascSortedRecords = records.sort(exports.getSortScoreForOrderRecords);
70
+ return direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;
71
+ };
72
+ exports.sortOrderRecords = sortOrderRecords;
73
+ const getLatestOfTwoUIOrderRecords = (orderA, orderB) => {
74
+ return (0, exports.getSortScoreForOrderRecords)(orderA, orderB) === 1 ? orderA : orderB;
75
+ };
76
+ exports.getLatestOfTwoUIOrderRecords = getLatestOfTwoUIOrderRecords;
77
+ const getLatestOfTwoOrderRecords = (orderA, orderB) => {
78
+ return (0, exports.getSortScoreForOrderRecords)(orderA, orderB) === 1 ? orderA : orderB;
79
+ };
80
+ exports.getLatestOfTwoOrderRecords = getLatestOfTwoOrderRecords;
81
+ const getUIOrderRecordsLaterThanTarget = (target, records) => records.filter((record) => (0, exports.getLatestOfTwoUIOrderRecords)(record, target) === record);
82
+ exports.getUIOrderRecordsLaterThanTarget = getUIOrderRecordsLaterThanTarget;
83
+ //# sourceMappingURL=sort.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sort.js","sourceRoot":"","sources":["../../../src/utils/orders/sort.ts"],"names":[],"mappings":";;;AAAA,yCAKyB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ionRecord,\n\tOrderRecord,\n} from '@drift-labs/sdk';\nimport {\n\tUIMatchedOrderRecordAndAction,\n\tUISerializableOrderActionRecord,\n} from '../../serializableTypes';\nimport { matchEnum } from '../enum';\n\nexport type PartialOrderActionRecord =\n\t| PartialUISerializableOrderActionRecord\n\t| PartialOrderActionEventRecord;\n\nexport type PartialUISerializableOrderActionRecord = Pick<\n\tUISerializableOrderActionRecord,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'oraclePrice'\n>;\n\nexport type PartialOrderActionEventRecord = Pick<\n\tEvent<OrderActionRecord>,\n\t| 'quoteAssetAmountFilled'\n\t| 'baseAssetAmountFilled'\n\t| 'ts'\n\t| 'slot'\n\t| 'action'\n\t| 'fillRecordId'\n\t| 'taker'\n\t| 'takerOrderBaseAssetAmount'\n\t| 'makerOrderBaseAssetAmount'\n\t| 'takerOrderCumulativeBaseAssetAmountFilled'\n\t| 'makerOrderCumulativeBaseAssetAmountFilled'\n\t| 'takerOrderCumulativeQuoteAssetAmountFilled'\n\t| 'makerOrderCumulativeQuoteAssetAmountFilled'\n>;\n\nconst getChronologicalValueForOrderAction = (action: OrderAction) => {\n\treturn matchEnum(action, OrderAction.PLACE)\n\t\t? 0\n\t\t: matchEnum(action, OrderAction.FILL)\n\t\t? 1\n\t\t: 2;\n};\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderRecords = (\n\torderA: { slot: number },\n\torderB: { slot: number }\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\treturn 0;\n};\n\n/**\n * Returns 1 if the first Order is chronologically later than the second Order, -1 if before, 0 if equal\n * @param orderA\n * @param orderB\n * @returns\n */\nexport const getSortScoreForOrderActionRecords = (\n\torderA: PartialOrderActionRecord,\n\torderB: PartialOrderActionRecord\n) => {\n\tif (orderA.slot !== orderB.slot) {\n\t\treturn orderA.slot > orderB.slot ? 1 : -1;\n\t}\n\n\tif (!matchEnum(orderA.action, orderB.action)) {\n\t\t// @ts-ignore\n\t\tconst orderAActionVal = getChronologicalValueForOrderAction(orderA.action);\n\t\t// @ts-ignore\n\t\tconst orderBActionVal = getChronologicalValueForOrderAction(orderB.action);\n\n\t\treturn orderAActionVal > orderBActionVal ? 1 : -1;\n\t}\n\t// @ts-ignore\n\tif (orderA.fillRecordId && orderB.fillRecordId) {\n\t\tif (!orderA.fillRecordId.eq(orderB.fillRecordId)) {\n\t\t\t// @ts-ignore\n\t\t\treturn orderA.fillRecordId.gt(orderB.fillRecordId) ? 1 : -1;\n\t\t}\n\t}\n\n\treturn 0;\n};\n\nexport const sortUIMatchedOrderRecordAndAction = (\n\trecords: UIMatchedOrderRecordAndAction[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort((a, b) =>\n\t\tgetSortScoreForOrderActionRecords(a.actionRecord, b.actionRecord)\n\t);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderActionRecords = (\n\trecords: PartialUISerializableOrderActionRecord[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderActionRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortUIOrderRecords = <T extends { slot: number }>(\n\trecords: T[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const sortOrderRecords = (\n\trecords: Event<OrderRecord>[],\n\tdirection: 'asc' | 'desc' = 'desc'\n) => {\n\tconst ascSortedRecords = records.sort(getSortScoreForOrderRecords);\n\n\treturn direction === 'desc' ? ascSortedRecords.reverse() : ascSortedRecords;\n};\n\nexport const getLatestOfTwoUIOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getLatestOfTwoOrderRecords = <T extends { slot: number }>(\n\torderA: T,\n\torderB: T\n) => {\n\treturn getSortScoreForOrderRecords(orderA, orderB) === 1 ? orderA : orderB;\n};\n\nexport const getUIOrderRecordsLaterThanTarget = <T extends { slot: number }>(\n\ttarget: T,\n\trecords: T[]\n) =>\n\trecords.filter(\n\t\t(record) => getLatestOfTwoUIOrderRecords(record, target) === record\n\t);\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './open';
2
+ export * from './user';
@@ -14,10 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./commonUiUtils"), exports);
18
- __exportStar(require("./market"), exports);
19
- __exportStar(require("./order"), exports);
20
- __exportStar(require("./trading"), exports);
17
+ __exportStar(require("./open"), exports);
21
18
  __exportStar(require("./user"), exports);
22
- __exportStar(require("./settings/settings"), exports);
23
19
  //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/positions/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAAuB;AACvB,yCAAuB","sourcesContent":["export * from './open';\nexport * from './user';\n"]}
@@ -0,0 +1,4 @@
1
+ import { BN, DriftClient, PerpMarketConfig, PerpPosition, User } from '@drift-labs/sdk';
2
+ import { OpenPosition } from '../../types';
3
+ declare const getOpenPositionData: (driftClient: DriftClient, userPositions: PerpPosition[], user: User, perpMarketLookup: PerpMarketConfig[], markPriceCallback?: (marketIndex: number) => BN) => OpenPosition[];
4
+ export { getOpenPositionData };
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.USER_UTILS = void 0;
3
+ exports.getOpenPositionData = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
- const types_1 = require("../types");
6
- const trading_1 = require("./trading");
7
- const utils_1 = require("../utils");
5
+ const types_1 = require("../../types");
6
+ const pnl_1 = require("../trading/pnl");
7
+ const enum_1 = require("../enum");
8
8
  const getOpenPositionData = (driftClient, userPositions, user, perpMarketLookup, markPriceCallback) => {
9
9
  const oracleGuardRails = driftClient.getStateAccount().oracleGuardRails;
10
10
  const newResult = userPositions
@@ -25,8 +25,8 @@ const getOpenPositionData = (driftClient, userPositions, user, perpMarketLookup,
25
25
  const entryPrice = (0, sdk_1.calculateEntryPrice)(position);
26
26
  const isShort = position.baseAssetAmount.isNeg();
27
27
  if (types_1.UIMarket.checkIsPredictionMarket(perpMarketConfig)) {
28
- const isResolved = utils_1.ENUM_UTILS.match(perpMarket === null || perpMarket === void 0 ? void 0 : perpMarket.status, sdk_1.MarketStatus.SETTLEMENT) ||
29
- utils_1.ENUM_UTILS.match(perpMarket === null || perpMarket === void 0 ? void 0 : perpMarket.status, sdk_1.MarketStatus.DELISTED);
28
+ const isResolved = enum_1.ENUM_UTILS.match(perpMarket === null || perpMarket === void 0 ? void 0 : perpMarket.status, sdk_1.MarketStatus.SETTLEMENT) ||
29
+ enum_1.ENUM_UTILS.match(perpMarket === null || perpMarket === void 0 ? void 0 : perpMarket.status, sdk_1.MarketStatus.DELISTED);
30
30
  if (isResolved) {
31
31
  const resolvedToNo = perpMarket.expiryPrice.lte(sdk_1.ZERO.add(perpMarket.amm.orderTickSize));
32
32
  const price = resolvedToNo
@@ -44,7 +44,7 @@ const getOpenPositionData = (driftClient, userPositions, user, perpMarketLookup,
44
44
  if (oraclePrice.lte(sdk_1.ZERO) && markPrice.gt(sdk_1.ZERO)) {
45
45
  oraclePrice = markPrice;
46
46
  }
47
- const pnlVsMark = trading_1.TRADING_UTILS.calculatePotentialProfit({
47
+ const pnlVsMark = (0, pnl_1.calculatePotentialProfit)({
48
48
  currentPositionSize: sdk_1.BigNum.from(position.baseAssetAmount.abs(), sdk_1.BASE_PRECISION_EXP),
49
49
  currentPositionDirection: isShort
50
50
  ? sdk_1.PositionDirection.SHORT
@@ -57,7 +57,7 @@ const getOpenPositionData = (driftClient, userPositions, user, perpMarketLookup,
57
57
  exitPrice: sdk_1.BigNum.from(markPrice, sdk_1.PRICE_PRECISION_EXP),
58
58
  takerFeeBps: 0,
59
59
  }).estimatedProfit.shiftTo(sdk_1.QUOTE_PRECISION_EXP).val;
60
- const pnlVsOracle = trading_1.TRADING_UTILS.calculatePotentialProfit({
60
+ const pnlVsOracle = (0, pnl_1.calculatePotentialProfit)({
61
61
  currentPositionSize: sdk_1.BigNum.from(position.baseAssetAmount.abs(), sdk_1.BASE_PRECISION_EXP),
62
62
  currentPositionDirection: isShort
63
63
  ? sdk_1.PositionDirection.SHORT
@@ -106,76 +106,5 @@ const getOpenPositionData = (driftClient, userPositions, user, perpMarketLookup,
106
106
  });
107
107
  return newResult;
108
108
  };
109
- const checkIfUserAccountExists = async (driftClient, config) => {
110
- let userPubKey;
111
- if (config.type === 'userPubKey') {
112
- userPubKey = config.userPubKey;
113
- }
114
- else {
115
- userPubKey = (0, sdk_1.getUserAccountPublicKeySync)(driftClient.program.programId, config.authority, config.subAccountId);
116
- }
117
- const accountInfo = await driftClient.connection.getAccountInfo(userPubKey);
118
- return accountInfo !== null;
119
- };
120
- /**
121
- * A user's max leverage for a market is stored on-chain in the `PerpPosition` struct of the `UserAccount`.
122
- * There are a few scenarios for how a market's max leverage is defined:
123
- *
124
- * 1. When the user does not have a position ("empty" or not) in the market in their `UserAccount` data,
125
- * and creates an order for the market, an "empty" `PerpPosition` will be upsert to the `UserAccount` data,
126
- * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up
127
- * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be
128
- * "empty" if the user does not have the max 8 perp positions open. The max leverage is then derived from
129
- * the max margin ratio set in the `PerpPosition` struct.
130
- *
131
- * 2. If the user has a position ("empty" or not), but no open orders and is provided with a saved max leverage,
132
- * the saved max leverage is used.
133
- *
134
- * 3. When the user does not have a position ("empty" or not), it is expected of the UI to store and persist
135
- * the max leverage in the UI client.
136
- *
137
- * 4. In cases where the user has a position before the market max leverage feature was shipped, the
138
- * position is not expected to have a max margin ratio set, and the UI should display the regular max
139
- * leverage for the market, unless the user is already in High Leverage Mode, in which case the UI should
140
- * display the high leverage max leverage for the market (if any).
141
- */
142
- const getUserMaxLeverageForMarket = (user, marketIndex, marketLeverageDetails, uiSavedMaxLeverage) => {
143
- // if no saved max leverage is provided, return the regular max leverage for the market
144
- const DEFAULT_MAX_LEVERAGE = uiSavedMaxLeverage !== null && uiSavedMaxLeverage !== void 0 ? uiSavedMaxLeverage : marketLeverageDetails.regularMaxLeverage;
145
- if (!user) {
146
- return DEFAULT_MAX_LEVERAGE;
147
- }
148
- const 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.
149
- if (!openOrClosedPosition) {
150
- return DEFAULT_MAX_LEVERAGE;
151
- }
152
- const positionHasMaxMarginRatioSet = !!openOrClosedPosition.maxMarginRatio;
153
- const isPositionOpen = !openOrClosedPosition.baseAssetAmount.eq(sdk_1.ZERO);
154
- const hasNoOpenOrders = openOrClosedPosition.openOrders === 0;
155
- if (positionHasMaxMarginRatioSet) {
156
- // Special case: open position with no orders - use UI saved value if available
157
- if (isPositionOpen && hasNoOpenOrders && uiSavedMaxLeverage) {
158
- return uiSavedMaxLeverage;
159
- }
160
- return parseFloat(((1 / openOrClosedPosition.maxMarginRatio) * 10000).toFixed(2));
161
- }
162
- if (isPositionOpen) {
163
- // user has an existing position from before PML ship (this means no max margin ratio set onchain yet)
164
- // display max leverage for the leverage mode their account is in
165
- const isUserInHighLeverageMode = user.isHighLeverageMode('Initial');
166
- const grandfatheredMaxLev = isUserInHighLeverageMode
167
- ? marketLeverageDetails.hasHighLeverage
168
- ? marketLeverageDetails.highLeverageMaxLeverage
169
- : marketLeverageDetails.regularMaxLeverage
170
- : marketLeverageDetails.regularMaxLeverage;
171
- return grandfatheredMaxLev;
172
- }
173
- // user has closed position with no margin ratio set, return default value
174
- return DEFAULT_MAX_LEVERAGE;
175
- };
176
- exports.USER_UTILS = {
177
- getOpenPositionData,
178
- checkIfUserAccountExists,
179
- getUserMaxLeverageForMarket,
180
- };
181
- //# sourceMappingURL=user.js.map
109
+ exports.getOpenPositionData = getOpenPositionData;
110
+ //# sourceMappingURL=open.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"open.js","sourceRoot":"","sources":["../../../src/utils/positions/open.ts"],"names":[],"mappings":";;;AAAA,yCAwByB;AACzB,uCAAqD;AACrD,wCAA0D;AAC1D,kCAAqC;AAErC,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,aAAa;SAC7C,MAAM,CACN,CAAC,QAAQ,EAAE,EAAE,CACZ,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,UAAI,CAAC;QAClC,CAAC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC,UAAI,CAAC,CACpC;SACA,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE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\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketConfig,\n\tPerpPosition,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tQUOTE_SPOT_MARKET_INDEX,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateCostBasis,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tcalculateUnsettledFundingPnl,\n\tisOracleValid,\n\tAMM_RESERVE_PRECISION,\n} from '@drift-labs/sdk';\nimport { OpenPosition, UIMarket } from '../../types';\nimport { calculatePotentialProfit } from '../trading/pnl';\nimport { ENUM_UTILS } from '../enum';\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 = 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 = 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\nexport { getOpenPositionData };\n"]}
@@ -0,0 +1,37 @@
1
+ import { DriftClient, PublicKey, User } from '@drift-labs/sdk';
2
+ declare const checkIfUserAccountExists: (driftClient: DriftClient, config: {
3
+ type: 'userPubKey';
4
+ userPubKey: PublicKey;
5
+ } | {
6
+ type: 'subAccountId';
7
+ subAccountId: number;
8
+ authority: PublicKey;
9
+ }) => Promise<boolean>;
10
+ /**
11
+ * A user's max leverage for a market is stored on-chain in the `PerpPosition` struct of the `UserAccount`.
12
+ * There are a few scenarios for how a market's max leverage is defined:
13
+ *
14
+ * 1. When the user does not have a position ("empty" or not) in the market in their `UserAccount` data,
15
+ * and creates an order for the market, an "empty" `PerpPosition` will be upsert to the `UserAccount` data,
16
+ * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up
17
+ * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be
18
+ * "empty" if the user does not have the max 8 perp positions open. The max leverage is then derived from
19
+ * the max margin ratio set in the `PerpPosition` struct.
20
+ *
21
+ * 2. If the user has a position ("empty" or not), but no open orders and is provided with a saved max leverage,
22
+ * the saved max leverage is used.
23
+ *
24
+ * 3. When the user does not have a position ("empty" or not), it is expected of the UI to store and persist
25
+ * the max leverage in the UI client.
26
+ *
27
+ * 4. In cases where the user has a position before the market max leverage feature was shipped, the
28
+ * position is not expected to have a max margin ratio set, and the UI should display the regular max
29
+ * leverage for the market, unless the user is already in High Leverage Mode, in which case the UI should
30
+ * display the high leverage max leverage for the market (if any).
31
+ */
32
+ declare const getUserMaxLeverageForMarket: (user: User | undefined, marketIndex: number, marketLeverageDetails: {
33
+ regularMaxLeverage: number;
34
+ highLeverageMaxLeverage: number;
35
+ hasHighLeverage: boolean;
36
+ }, uiSavedMaxLeverage?: number) => number;
37
+ export { checkIfUserAccountExists, getUserMaxLeverageForMarket };
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getUserMaxLeverageForMarket = exports.checkIfUserAccountExists = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ const checkIfUserAccountExists = async (driftClient, config) => {
6
+ let userPubKey;
7
+ if (config.type === 'userPubKey') {
8
+ userPubKey = config.userPubKey;
9
+ }
10
+ else {
11
+ userPubKey = (0, sdk_1.getUserAccountPublicKeySync)(driftClient.program.programId, config.authority, config.subAccountId);
12
+ }
13
+ const accountInfo = await driftClient.connection.getAccountInfo(userPubKey);
14
+ return accountInfo !== null;
15
+ };
16
+ exports.checkIfUserAccountExists = checkIfUserAccountExists;
17
+ /**
18
+ * A user's max leverage for a market is stored on-chain in the `PerpPosition` struct of the `UserAccount`.
19
+ * There are a few scenarios for how a market's max leverage is defined:
20
+ *
21
+ * 1. When the user does not have a position ("empty" or not) in the market in their `UserAccount` data,
22
+ * and creates an order for the market, an "empty" `PerpPosition` will be upsert to the `UserAccount` data,
23
+ * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up
24
+ * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be
25
+ * "empty" if the user does not have the max 8 perp positions open. The max leverage is then derived from
26
+ * the max margin ratio set in the `PerpPosition` struct.
27
+ *
28
+ * 2. If the user has a position ("empty" or not), but no open orders and is provided with a saved max leverage,
29
+ * the saved max leverage is used.
30
+ *
31
+ * 3. When the user does not have a position ("empty" or not), it is expected of the UI to store and persist
32
+ * the max leverage in the UI client.
33
+ *
34
+ * 4. In cases where the user has a position before the market max leverage feature was shipped, the
35
+ * position is not expected to have a max margin ratio set, and the UI should display the regular max
36
+ * leverage for the market, unless the user is already in High Leverage Mode, in which case the UI should
37
+ * display the high leverage max leverage for the market (if any).
38
+ */
39
+ const getUserMaxLeverageForMarket = (user, marketIndex, marketLeverageDetails, uiSavedMaxLeverage) => {
40
+ // if no saved max leverage is provided, return the regular max leverage for the market
41
+ const DEFAULT_MAX_LEVERAGE = uiSavedMaxLeverage !== null && uiSavedMaxLeverage !== void 0 ? uiSavedMaxLeverage : marketLeverageDetails.regularMaxLeverage;
42
+ if (!user) {
43
+ return DEFAULT_MAX_LEVERAGE;
44
+ }
45
+ const 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.
46
+ if (!openOrClosedPosition) {
47
+ return DEFAULT_MAX_LEVERAGE;
48
+ }
49
+ const positionHasMaxMarginRatioSet = !!openOrClosedPosition.maxMarginRatio;
50
+ const isPositionOpen = !openOrClosedPosition.baseAssetAmount.eq(sdk_1.ZERO);
51
+ const hasNoOpenOrders = openOrClosedPosition.openOrders === 0;
52
+ if (positionHasMaxMarginRatioSet) {
53
+ // Special case: open position with no orders - use UI saved value if available
54
+ if (isPositionOpen && hasNoOpenOrders && uiSavedMaxLeverage) {
55
+ return uiSavedMaxLeverage;
56
+ }
57
+ return parseFloat(((1 / openOrClosedPosition.maxMarginRatio) * 10000).toFixed(2));
58
+ }
59
+ if (isPositionOpen) {
60
+ // user has an existing position from before PML ship (this means no max margin ratio set onchain yet)
61
+ // display max leverage for the leverage mode their account is in
62
+ const isUserInHighLeverageMode = user.isHighLeverageMode('Initial');
63
+ const grandfatheredMaxLev = isUserInHighLeverageMode
64
+ ? marketLeverageDetails.hasHighLeverage
65
+ ? marketLeverageDetails.highLeverageMaxLeverage
66
+ : marketLeverageDetails.regularMaxLeverage
67
+ : marketLeverageDetails.regularMaxLeverage;
68
+ return grandfatheredMaxLev;
69
+ }
70
+ // user has closed position with no margin ratio set, return default value
71
+ return DEFAULT_MAX_LEVERAGE;
72
+ };
73
+ exports.getUserMaxLeverageForMarket = getUserMaxLeverageForMarket;
74
+ //# sourceMappingURL=user.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user.js","sourceRoot":"","sources":["../../../src/utils/positions/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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;AAEiC,kEAA2B","sourcesContent":["import {\n\tDriftClient,\n\tPublicKey,\n\tUser,\n\tZERO,\n\tgetUserAccountPublicKeySync,\n} from '@drift-labs/sdk';\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 { checkIfUserAccountExists, getUserMaxLeverageForMarket };\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settings.js","sourceRoot":"","sources":["../../../src/utils/settings/settings.ts"],"names":[],"mappings":";;;AAAA,iCAAuC;AAUvC,IAAY,kBAIX;AAJD,WAAY,kBAAkB;IAC7B,2CAAqB,CAAA;IACrB,iDAA2B,CAAA;IAC3B,uDAAiC,CAAA;AAClC,CAAC,EAJW,kBAAkB,kCAAlB,kBAAkB,QAI7B;AAWD;;;;;;;;;GASG;AACI,MAAM,4BAA4B,GAAG,CAC3C,uBAA+B,EAC/B,OAAgB,EAChB,OAA+B,EAC/B,IAAwB,EACxB,qBAA6B,EAC7B,sBAA8B,EACL,EAAE,CAA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AK,CAAC,CAAC;gBAErB,IAAI,oBAAoB,EAAE,CAAC;oBAC1B,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBAC9B,CAAC;YACF,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,MAAM,oBAAoB,GAAG,iBAAiB,CAAC,MAAM,GAAG,CAAC,CAAC;QAE1D,WAAW,CAAC,OAAO,GAAG,IAAA,eAAO,EAAC,WAAW,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;YAC5D,KAAK,CAAC,OAAO,GAAG,UAAU,CAAC;QAC5B,CAAC,CAAC,CAAC;QAEH,IAAI,yBAAyB,GAAG,EAAE,CAAC;QAEnC,IAAI,iBAAiB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACpC,yBAAyB,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC,qBAAqB,CAAC;QACxE,CAAC;QAED,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAClC,yBAAyB,GAAG,iEAAiE,iBAAiB;iBAC5G,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC;iBAC1C,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAChB,CAAC;QAED,OAAO;YACN,wBAAwB,EAAE,oBAAoB;YAC9C,mBAAmB,EAAE,WAAW,CAAC,OAAO;YACxC,yBAAyB;SACzB,CAAC;IACH,CAAC;IAED,YAAY,KAAgC;QAC3C,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACpB,CAAC;CACD;AArED,4DAqEC","sourcesContent":["import { Draft, produce } from 'immer';\n\nexport declare type TransformerFunction<S> = (draft: Draft<S>) => {\n\ttransformationWasApplied: boolean;\n};\n\ntype VersionedSettings = Record<string, unknown> & {\n\tversion?: number;\n};\n\nexport enum SettingHandlerType {\n\tAdditive = 'additive',\n\tSubtractive = 'subtractive',\n\tTransformative = 'transformative',\n}\n\nexport type SettingsVersionRule<T = VersionedSettings> = {\n\tminVersionDiscriminator: number;\n\tsetting: keyof T;\n\thandler: TransformerFunction<T>;\n\ttype: SettingHandlerType;\n\tlongChangeDescription: string;\n\tshortChangeDescription: string;\n};\n\n/**\n *\n * @param minVersionDiscriminator\n * @param setting\n * @param handler\n * @param type\n * @param longChangeDescription : This description will be returned if this was the ONLY transformation rule that needed to apply. E.g. : \"Priority fee upgrades were recently release, and your priority fee settings were recently reset to defaults.\"\n * @param shortChangeDescription : This description will be returned if this was one of many transformation rules that needed to apply, they will be presented in a list. E.g. : \"Your priority fee settings were recently reset to defaults.\" => \"The following settings were changed to support new features : 'Your priority fee settings were recently reset to defaults.', '{something else}', etc.\"\"\n * @returns\n */\nexport const VersionedSettingsRuleFactory = <T = VersionedSettings>(\n\tminVersionDiscriminator: number,\n\tsetting: keyof T,\n\thandler: TransformerFunction<T>,\n\ttype: SettingHandlerType,\n\tlongChangeDescription: string,\n\tshortChangeDescription: string\n): SettingsVersionRule<T> => ({\n\tminVersionDiscriminator,\n\tsetting,\n\thandler,\n\ttype,\n\tlongChangeDescription,\n\tshortChangeDescription,\n});\n\nexport type VersionedSettingsRules<T extends VersionedSettings> =\n\tSettingsVersionRule<T>[];\n\n/**\n * The versioned settings handler ensures that old settings can be upgraded into newer versioned settings. It reports back on any changes if they were applied.\n */\nexport class VersionedSettingsHandler<T extends VersionedSettings> {\n\tprivate rules: VersionedSettingsRules<T>;\n\n\t/**\n\t * Applies each of the handlers in order, depending on the version of the incoming settings.\n\t *\n\t * Returns the new settings, with a list of change descriptions and an updated version number.\n\t * @param settings\n\t */\n\tapply(settings: T) {\n\t\tconst sortedRules = this.rules.sort(\n\t\t\t(a, b) => a.minVersionDiscriminator - b.minVersionDiscriminator\n\t\t);\n\n\t\tconst rulesToApply = sortedRules.filter((rule) => {\n\t\t\tif (!settings[rule.setting] || !settings.version) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn rule.minVersionDiscriminator > settings?.version;\n\t\t});\n\n\t\tconst maxVersion = Math.max(\n\t\t\t...sortedRules.map((rule) => rule.minVersionDiscriminator),\n\t\t\tsettings.version ?? -1\n\t\t);\n\n\t\tconst newSettings = { current: settings };\n\n\t\tconst transformsApplied: SettingsVersionRule<T>[] = [];\n\n\t\trulesToApply.forEach((rule) => {\n\t\t\tnewSettings.current = produce(newSettings.current, (draft) => {\n\t\t\t\tconst { transformationWasApplied: ruleTransformApplied } =\n\t\t\t\t\trule.handler(draft);\n\n\t\t\t\tif (ruleTransformApplied) {\n\t\t\t\t\ttransformsApplied.push(rule);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tconst aTransformWasApplied = transformsApplied.length > 0;\n\n\t\tnewSettings.current = produce(newSettings.current, (draft) => {\n\t\t\tdraft.version = maxVersion;\n\t\t});\n\n\t\tlet transformationDescription = '';\n\n\t\tif (transformsApplied.length === 1) {\n\t\t\ttransformationDescription = transformsApplied[0].longChangeDescription;\n\t\t}\n\n\t\tif (transformsApplied.length > 1) {\n\t\t\ttransformationDescription = `The following settings were changed to support new features : ${transformsApplied\n\t\t\t\t.map((rule) => rule.shortChangeDescription)\n\t\t\t\t.join(', ')}`;\n\t\t}\n\n\t\treturn {\n\t\t\ttransformationWasApplied: aTransformWasApplied,\n\t\t\ttransformedSettings: newSettings.current,\n\t\t\ttransformationDescription,\n\t\t};\n\t}\n\n\tconstructor(rules: VersionedSettingsRules<T>) {\n\t\tthis.rules = rules;\n\t}\n}\n"]}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Recursively converts various types into printable strings.
3
+ */
4
+ export declare function toPrintableObject(obj: unknown,
5
+ /** Used to guard against circular refs during recursion. */
6
+ seen?: WeakSet<object>): unknown;
7
+ export declare function convertStringValuesToNumbers<T>(obj: T): T;
8
+ /**
9
+ * Returns an array of an object's string values (deep).
10
+ */
11
+ export declare function extractStringValuesFromObject(value: object): string[];
@@ -1,56 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractStringValuesFromObject = exports.convertStringValuesToNumbers = exports.toPrintableObject = exports.lastOrderStatusToNormalEng = exports.disallowNegativeStringInput = exports.lowerCaseNonFirstWords = exports.splitByCapitalLetters = exports.abbreviateAccountName = exports.isValidBase58 = void 0;
3
+ exports.extractStringValuesFromObject = exports.convertStringValuesToNumbers = exports.toPrintableObject = void 0;
4
4
  const sdk_1 = require("@drift-labs/sdk");
5
- const isValidBase58 = (str) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(str);
6
- exports.isValidBase58 = isValidBase58;
7
- function abbreviateAccountName(name, size = 8, opts) {
8
- if (name.length <= size)
9
- return name;
10
- if (opts === null || opts === void 0 ? void 0 : opts.ellipsisMiddle) {
11
- const length = name.length;
12
- const sizeMid = Math.floor(size / 2);
13
- return name.slice(0, sizeMid) + '...' + name.slice(length - sizeMid);
14
- }
15
- return name.slice(0, size) + '...';
16
- }
17
- exports.abbreviateAccountName = abbreviateAccountName;
18
- function splitByCapitalLetters(word) {
19
- return word.replace(/([A-Z])/g, ' $1').trim();
20
- }
21
- exports.splitByCapitalLetters = splitByCapitalLetters;
22
- function lowerCaseNonFirstWords(sentence) {
23
- const words = sentence.split(' ');
24
- for (let i = 1; i < words.length; i++) {
25
- words[i] = words[i].toLowerCase();
26
- }
27
- return words.join(' ');
28
- }
29
- exports.lowerCaseNonFirstWords = lowerCaseNonFirstWords;
30
- const disallowNegativeStringInput = (str) => {
31
- if (str && str.charAt(0) === '-') {
32
- return '0';
33
- }
34
- return str;
35
- };
36
- exports.disallowNegativeStringInput = disallowNegativeStringInput;
37
- /**
38
- * LastOrder status types from https://github.com/drift-labs/infrastructure-v3/blob/8ab1888eaaaed96228406b562d4a399729d042d7/packages/common/src/types/index.ts#L221
39
- */
40
- const LAST_ORDER_STATUS_LABELS = {
41
- open: 'Open',
42
- filled: 'Filled',
43
- partial_fill: 'Partially Filled',
44
- cancelled: 'Canceled',
45
- partial_fill_cancelled: 'Partially Filled & Canceled',
46
- expired: 'Expired',
47
- trigger: 'Triggered',
48
- };
49
- function lastOrderStatusToNormalEng(status) {
50
- var _a;
51
- return (_a = LAST_ORDER_STATUS_LABELS[status]) !== null && _a !== void 0 ? _a : status;
52
- }
53
- exports.lastOrderStatusToNormalEng = lastOrderStatusToNormalEng;
54
5
  /**
55
6
  * Recursively converts various types into printable strings.
56
7
  */
@@ -118,4 +69,4 @@ function extractStringValuesFromObject(value) {
118
69
  return [];
119
70
  }
120
71
  exports.extractStringValuesFromObject = extractStringValuesFromObject;
121
- //# sourceMappingURL=strings.js.map
72
+ //# sourceMappingURL=convert.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convert.js","sourceRoot":"","sources":["../../../src/utils/strings/convert.ts"],"names":[],"mappings":";;;AAAA,yCAA6C;AAE7C;;GAEG;AACH,SAAgB,iBAAiB,CAChC,GAAY;AACZ,4DAA4D;AAC5D,OAAwB,IAAI,OAAO,EAAE;IAErC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QACjB,OAAO,IAAI,CAAC;IACb,CAAC;IAED,IAAI,GAAG,YAAY,YAAM,IAAI,QAAE,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACtE,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;IACvB,CAAC;IAED,IAAI,GAAG,YAAY,IAAI,EAAE,CAAC;QACzB,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC;QAE3B,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YACxB,OAAO,cAAc,CAAC;QACvB,CAAC;QAED,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC;IAC1B,CAAC;IAED,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC7B,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YACnB,OAAO,YAAY,CAAC;QACrB,CAAC;QAED,IAAI,CAA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,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/B,OAAO,CAAC,KAAK,CAAC,CAAC;IAChB,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,KAAK,CAAC,OAAO,CAAC,6BAA6B,CAAC,CAAC;IACrD,CAAC;IAED,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,6BAA6B,CAAC,CAAC;IACpE,CAAC;IAED,OAAO,EAAE,CAAC;AACX,CAAC;AAdD,sEAcC","sourcesContent":["import { BN, BigNum } from '@drift-labs/sdk';\n\n/**\n * Recursively converts various types into printable strings.\n */\nexport function toPrintableObject(\n\tobj: unknown,\n\t/** Used to guard against circular refs during recursion. */\n\tseen: WeakSet<object> = new WeakSet()\n): unknown {\n\tif (obj == null) {\n\t\treturn null;\n\t}\n\n\tif (obj instanceof BigNum || BN.isBN(obj) || typeof obj === 'bigint') {\n\t\treturn obj.toString();\n\t}\n\n\tif (obj instanceof Date) {\n\t\tconst time = obj.getTime();\n\n\t\tif (Number.isNaN(time)) {\n\t\t\treturn 'Invalid Date';\n\t\t}\n\n\t\treturn obj.toISOString();\n\t}\n\n\tif (typeof obj === 'object') {\n\t\tif (seen.has(obj)) {\n\t\t\treturn '[Circular]';\n\t\t}\n\n\t\tseen.add(obj);\n\n\t\tif (Array.isArray(obj)) {\n\t\t\treturn obj.map((value) => toPrintableObject(value, seen));\n\t\t}\n\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(obj).map(([key, value]) => [\n\t\t\t\tkey,\n\t\t\t\ttoPrintableObject(value, seen),\n\t\t\t])\n\t\t);\n\t}\n\n\treturn obj;\n}\n\nexport function convertStringValuesToNumbers<T>(obj: T): T {\n\tif (typeof obj === 'string' && !isNaN(Number(obj))) {\n\t\treturn Number(obj) as T;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\treturn obj.map(convertStringValuesToNumbers) as T;\n\t}\n\n\tif (obj !== null && typeof obj === 'object') {\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(obj).map(([key, value]) => [\n\t\t\t\tkey,\n\t\t\t\tconvertStringValuesToNumbers(value),\n\t\t\t])\n\t\t) as T;\n\t}\n\n\treturn obj;\n}\n\n/**\n * Returns an array of an object's string values (deep).\n */\nexport function extractStringValuesFromObject(value: object): string[] {\n\tif (typeof value === 'string') {\n\t\treturn [value];\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn value.flatMap(extractStringValuesFromObject);\n\t}\n\n\tif (value && typeof value === 'object') {\n\t\treturn Object.values(value).flatMap(extractStringValuesFromObject);\n\t}\n\n\treturn [];\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import { PublicKey } from '@drift-labs/sdk';
2
+ export declare const abbreviateAddress: (address: string | PublicKey, length?: number) => string;
3
+ /**
4
+ * Trim trailing zeros from a numerical string
5
+ * @param str - numerical string to format
6
+ * @param zerosToShow - max number of zeros to show after the decimal. Similar to number.toFixed() but won't trim non-zero values. Optional, default value is 1
7
+ */
8
+ export declare const trimTrailingZeros: (str: string, zerosToShow?: number) => string;
9
+ export declare const toSnakeCase: (str: string) => string;
10
+ export declare const toCamelCase: (str: string) => string;
11
+ export declare const normalizeBaseAssetSymbol: (symbol: string) => string;
12
+ export declare function abbreviateAccountName(name: string, size?: number, opts?: {
13
+ ellipsisMiddle?: boolean;
14
+ }): string;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.abbreviateAccountName = exports.normalizeBaseAssetSymbol = exports.toCamelCase = exports.toSnakeCase = exports.trimTrailingZeros = exports.abbreviateAddress = void 0;
4
+ const cache_1 = require("../core/cache");
5
+ const abbreviateAddress = (address, length = 4) => {
6
+ if (!address)
7
+ return '';
8
+ const authString = address.toString();
9
+ return (0, cache_1.getCachedUiString)('abbreviate', authString, length);
10
+ };
11
+ exports.abbreviateAddress = abbreviateAddress;
12
+ /**
13
+ * Trim trailing zeros from a numerical string
14
+ * @param str - numerical string to format
15
+ * @param zerosToShow - max number of zeros to show after the decimal. Similar to number.toFixed() but won't trim non-zero values. Optional, default value is 1
16
+ */
17
+ const trimTrailingZeros = (str, zerosToShow = 1) => {
18
+ // Ignore strings with no decimal point
19
+ if (!str.includes('.'))
20
+ return str;
21
+ const sides = str.split('.');
22
+ sides[1] = sides[1].replace(/0+$/, '');
23
+ if (sides[1].length < zerosToShow) {
24
+ const zerosToAdd = zerosToShow - sides[1].length;
25
+ sides[1] = `${sides[1]}${Array(zerosToAdd).fill('0').join('')}`;
26
+ }
27
+ if (sides[1].length === 0) {
28
+ return sides[0];
29
+ }
30
+ else {
31
+ return sides.join('.');
32
+ }
33
+ };
34
+ exports.trimTrailingZeros = trimTrailingZeros;
35
+ const toSnakeCase = (str) => str.replace(/[^\w]/g, '_').toLowerCase();
36
+ exports.toSnakeCase = toSnakeCase;
37
+ const toCamelCase = (str) => {
38
+ const words = str.split(/[_\-\s]+/); // split on underscores, hyphens, and spaces
39
+ const firstWord = words[0].toLowerCase();
40
+ const restWords = words
41
+ .slice(1)
42
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
43
+ return [firstWord, ...restWords].join('');
44
+ };
45
+ exports.toCamelCase = toCamelCase;
46
+ const normalizeBaseAssetSymbol = (symbol) => {
47
+ return symbol.replace(/^1M/, '');
48
+ };
49
+ exports.normalizeBaseAssetSymbol = normalizeBaseAssetSymbol;
50
+ function abbreviateAccountName(name, size = 8, opts) {
51
+ if (name.length <= size)
52
+ return name;
53
+ if (opts === null || opts === void 0 ? void 0 : opts.ellipsisMiddle) {
54
+ const length = name.length;
55
+ const sizeMid = Math.floor(size / 2);
56
+ return name.slice(0, sizeMid) + '...' + name.slice(length - sizeMid);
57
+ }
58
+ return name.slice(0, size) + '...';
59
+ }
60
+ exports.abbreviateAccountName = abbreviateAccountName;
61
+ //# s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AM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;QAErC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,KAAK,CAAC;AACpC,CAAC;AAjBD,sDAiBC","sourcesContent":["import { PublicKey } from '@drift-labs/sdk';\nimport { getCachedUiString } from '../core/cache';\n\nexport const abbreviateAddress = (address: string | PublicKey, length = 4) => {\n\tif (!address) return '';\n\tconst authString = address.toString();\n\treturn getCachedUiString('abbreviate', authString, length);\n};\n\n/**\n * Trim trailing zeros from a numerical string\n * @param str - numerical string to format\n * @param zerosToShow - max number of zeros to show after the decimal. Similar to number.toFixed() but won't trim non-zero values. Optional, default value is 1\n */\nexport const trimTrailingZeros = (str: string, zerosToShow = 1) => {\n\t// Ignore strings with no decimal point\n\tif (!str.includes('.')) return str;\n\n\tconst sides = str.split('.');\n\n\tsides[1] = sides[1].replace(/0+$/, '');\n\n\tif (sides[1].length < zerosToShow) {\n\t\tconst zerosToAdd = zerosToShow - sides[1].length;\n\t\tsides[1] = `${sides[1]}${Array(zerosToAdd).fill('0').join('')}`;\n\t}\n\n\tif (sides[1].length === 0) {\n\t\treturn sides[0];\n\t} else {\n\t\treturn sides.join('.');\n\t}\n};\n\nexport const toSnakeCase = (str: string): string =>\n\tstr.replace(/[^\\w]/g, '_').toLowerCase();\n\nexport const toCamelCase = (str: string): string => {\n\tconst words = str.split(/[_\\-\\s]+/); // split on underscores, hyphens, and spaces\n\tconst firstWord = words[0].toLowerCase();\n\tconst restWords = words\n\t\t.slice(1)\n\t\t.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());\n\treturn [firstWord, ...restWords].join('');\n};\n\nexport const normalizeBaseAssetSymbol = (symbol: string) => {\n\treturn symbol.replace(/^1M/, '');\n};\n\nexport function abbreviateAccountName(\n\tname: string,\n\tsize = 8,\n\topts?: {\n\t\tellipsisMiddle?: boolean;\n\t}\n) {\n\tif (name.length <= size) return name;\n\n\tif (opts?.ellipsisMiddle) {\n\t\tconst length = name.length;\n\t\tconst sizeMid = Math.floor(size / 2);\n\n\t\treturn name.slice(0, sizeMid) + '...' + name.slice(length - sizeMid);\n\t}\n\n\treturn name.slice(0, size) + '...';\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export * from './convert';
2
+ export * from './format';
3
+ export * from './parse';
4
+ export * from './status';