@drift-labs/sdk 0.2.0-master.4 → 0.2.0-master.41

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 (247) hide show
  1. package/README.md +27 -27
  2. package/lib/accounts/bulkAccountLoader.d.ts +2 -0
  3. package/lib/accounts/bulkAccountLoader.js +36 -29
  4. package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
  5. package/lib/accounts/bulkUserStatsSubscription.js +21 -0
  6. package/lib/accounts/bulkUserSubscription.d.ts +2 -2
  7. package/lib/accounts/bulkUserSubscription.js +0 -1
  8. package/lib/accounts/fetch.d.ts +2 -1
  9. package/lib/accounts/fetch.js +9 -1
  10. package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
  11. package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
  12. package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
  13. package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
  14. package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
  15. package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
  16. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  17. package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
  18. package/lib/accounts/types.d.ts +26 -15
  19. package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
  20. package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
  21. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  22. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  23. package/lib/addresses/marketAddresses.d.ts +1 -3
  24. package/lib/addresses/marketAddresses.js +1 -1
  25. package/lib/addresses/pda.d.ts +15 -9
  26. package/lib/addresses/pda.js +73 -35
  27. package/lib/adminClient.d.ts +65 -0
  28. package/lib/adminClient.js +637 -0
  29. package/lib/config.d.ts +9 -9
  30. package/lib/config.js +25 -21
  31. package/lib/constants/numericConstants.d.ts +30 -12
  32. package/lib/constants/numericConstants.js +41 -21
  33. package/lib/constants/perpMarkets.d.ts +18 -0
  34. package/lib/constants/{markets.js → perpMarkets.js} +7 -7
  35. package/lib/constants/spotMarkets.d.ts +19 -0
  36. package/lib/constants/spotMarkets.js +53 -0
  37. package/lib/dlob/DLOB.d.ts +82 -0
  38. package/lib/dlob/DLOB.js +694 -0
  39. package/lib/dlob/DLOBNode.d.ts +54 -0
  40. package/lib/dlob/DLOBNode.js +77 -0
  41. package/lib/dlob/NodeList.d.ts +27 -0
  42. package/lib/dlob/NodeList.js +144 -0
  43. package/lib/driftClient.d.ts +234 -0
  44. package/lib/driftClient.js +2108 -0
  45. package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
  46. package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
  47. package/lib/events/eventList.js +3 -0
  48. package/lib/events/eventSubscriber.d.ts +5 -2
  49. package/lib/events/eventSubscriber.js +25 -11
  50. package/lib/events/fetchLogs.d.ts +13 -2
  51. package/lib/events/fetchLogs.js +40 -12
  52. package/lib/events/pollingLogProvider.d.ts +2 -1
  53. package/lib/events/pollingLogProvider.js +7 -3
  54. package/lib/events/sort.js +8 -11
  55. package/lib/events/types.d.ts +11 -3
  56. package/lib/events/types.js +8 -0
  57. package/lib/events/webSocketLogProvider.js +1 -1
  58. package/lib/examples/makeTradeExample.js +30 -18
  59. package/lib/factory/bigNum.d.ts +8 -4
  60. package/lib/factory/bigNum.js +109 -19
  61. package/lib/idl/drift.json +8386 -0
  62. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  63. package/lib/index.d.ts +30 -13
  64. package/lib/index.js +30 -13
  65. package/lib/math/amm.d.ts +9 -6
  66. package/lib/math/amm.js +91 -38
  67. package/lib/math/conversion.js +1 -1
  68. package/lib/math/exchangeStatus.d.ts +4 -0
  69. package/lib/math/exchangeStatus.js +18 -0
  70. package/lib/math/funding.d.ts +6 -6
  71. package/lib/math/funding.js +23 -21
  72. package/lib/math/insurance.d.ts +4 -0
  73. package/lib/math/insurance.js +27 -0
  74. package/lib/math/margin.d.ts +11 -0
  75. package/lib/math/margin.js +82 -0
  76. package/lib/math/market.d.ts +14 -9
  77. package/lib/math/market.js +70 -10
  78. package/lib/math/oracles.d.ts +4 -0
  79. package/lib/math/oracles.js +36 -8
  80. package/lib/math/orders.d.ts +16 -6
  81. package/lib/math/orders.js +97 -17
  82. package/lib/math/position.d.ts +27 -13
  83. package/lib/math/position.js +92 -36
  84. package/lib/math/repeg.js +17 -8
  85. package/lib/math/spotBalance.d.ts +22 -0
  86. package/lib/math/spotBalance.js +192 -0
  87. package/lib/math/spotMarket.d.ts +4 -0
  88. package/lib/math/spotMarket.js +8 -0
  89. package/lib/math/spotPosition.d.ts +6 -0
  90. package/lib/math/spotPosition.js +23 -0
  91. package/lib/math/trade.d.ts +10 -10
  92. package/lib/math/trade.js +27 -31
  93. package/lib/oracles/pythClient.js +1 -1
  94. package/lib/oracles/quoteAssetOracleClient.js +1 -1
  95. package/lib/oracles/switchboardClient.js +1 -1
  96. package/lib/orderParams.d.ts +4 -4
  97. package/lib/orderParams.js +12 -4
  98. package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
  99. package/lib/serum/serumFulfillmentConfigMap.js +17 -0
  100. package/lib/serum/serumSubscriber.d.ts +27 -0
  101. package/lib/serum/serumSubscriber.js +56 -0
  102. package/lib/serum/types.d.ts +11 -0
  103. package/lib/{clearingHouseUserConfig.js → serum/types.js} +0 -0
  104. package/lib/slot/SlotSubscriber.d.ts +7 -0
  105. package/lib/slot/SlotSubscriber.js +3 -0
  106. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  107. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  108. package/lib/tx/retryTxSender.d.ts +1 -1
  109. package/lib/tx/retryTxSender.js +13 -4
  110. package/lib/tx/types.d.ts +1 -1
  111. package/lib/tx/utils.js +1 -1
  112. package/lib/types.d.ts +688 -216
  113. package/lib/types.js +153 -24
  114. package/lib/user.d.ts +228 -0
  115. package/lib/user.js +959 -0
  116. package/lib/userConfig.d.ts +14 -0
  117. package/lib/userConfig.js +2 -0
  118. package/lib/userMap/userMap.d.ts +41 -0
  119. package/lib/userMap/userMap.js +85 -0
  120. package/lib/userMap/userStatsMap.d.ts +19 -0
  121. package/lib/userMap/userStatsMap.js +68 -0
  122. package/lib/userName.d.ts +1 -0
  123. package/lib/userName.js +3 -2
  124. package/lib/userStats.d.ts +18 -0
  125. package/lib/userStats.js +49 -0
  126. package/lib/userStatsConfig.d.ts +14 -0
  127. package/lib/userStatsConfig.js +2 -0
  128. package/lib/util/computeUnits.js +1 -1
  129. package/lib/util/getTokenAddress.d.ts +2 -0
  130. package/lib/util/getTokenAddress.js +9 -0
  131. package/package.json +11 -4
  132. package/src/accounts/bulkAccountLoader.ts +44 -34
  133. package/src/accounts/bulkUserStatsSubscription.ts +33 -0
  134. package/src/accounts/bulkUserSubscription.ts +2 -3
  135. package/src/accounts/fetch.ts +27 -2
  136. package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
  137. package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
  138. package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
  139. package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
  140. package/src/accounts/types.ts +35 -15
  141. package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
  142. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  143. package/src/addresses/marketAddresses.ts +3 -4
  144. package/src/addresses/pda.ts +105 -33
  145. package/src/adminClient.ts +1207 -0
  146. package/src/assert/assert.js +9 -0
  147. package/src/config.ts +37 -31
  148. package/src/constants/numericConstants.ts +58 -24
  149. package/src/constants/{markets.ts → perpMarkets.ts} +10 -10
  150. package/src/constants/spotMarkets.ts +73 -0
  151. package/src/dlob/DLOB.ts +1120 -0
  152. package/src/dlob/DLOBNode.ts +155 -0
  153. package/src/dlob/NodeList.ts +195 -0
  154. package/src/driftClient.ts +3594 -0
  155. package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
  156. package/src/events/eventList.js +77 -0
  157. package/src/events/eventList.ts +3 -0
  158. package/src/events/eventSubscriber.ts +36 -14
  159. package/src/events/fetchLogs.ts +55 -13
  160. package/src/events/pollingLogProvider.ts +11 -3
  161. package/src/events/sort.ts +11 -15
  162. package/src/events/types.ts +27 -2
  163. package/src/events/webSocketLogProvider.ts +1 -1
  164. package/src/examples/makeTradeExample.js +157 -0
  165. package/src/examples/makeTradeExample.ts +44 -28
  166. package/src/factory/bigNum.ts +150 -22
  167. package/src/idl/drift.json +8386 -0
  168. package/src/idl/pyth.json +98 -2
  169. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  170. package/src/index.ts +30 -13
  171. package/src/math/amm.ts +161 -48
  172. package/src/math/conversion.ts +2 -2
  173. package/src/math/exchangeStatus.ts +31 -0
  174. package/src/math/funding.ts +41 -31
  175. package/src/math/insurance.ts +35 -0
  176. package/src/math/margin.ts +133 -0
  177. package/src/math/market.ts +143 -14
  178. package/src/math/oracles.ts +63 -9
  179. package/src/math/orders.ts +168 -26
  180. package/src/math/position.ts +136 -58
  181. package/src/math/repeg.ts +19 -9
  182. package/src/math/spotBalance.ts +319 -0
  183. package/src/math/spotMarket.ts +9 -0
  184. package/src/math/spotPosition.ts +47 -0
  185. package/src/math/trade.ts +33 -37
  186. package/src/oracles/pythClient.ts +2 -2
  187. package/src/oracles/quoteAssetOracleClient.ts +2 -2
  188. package/src/oracles/switchboardClient.ts +2 -2
  189. package/src/orderParams.ts +16 -8
  190. package/src/serum/serumFulfillmentConfigMap.ts +26 -0
  191. package/src/serum/serumSubscriber.ts +99 -0
  192. package/src/serum/types.ts +13 -0
  193. package/src/slot/SlotSubscriber.ts +11 -1
  194. package/src/token/index.js +38 -0
  195. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  196. package/src/tx/retryTxSender.ts +16 -5
  197. package/src/tx/types.js +2 -0
  198. package/src/tx/types.ts +2 -1
  199. package/src/tx/utils.js +17 -0
  200. package/src/tx/utils.ts +1 -1
  201. package/src/types.ts +650 -189
  202. package/src/user.ts +1599 -0
  203. package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
  204. package/src/userMap/userMap.ts +124 -0
  205. package/src/userMap/userStatsMap.ts +108 -0
  206. package/src/userName.ts +2 -1
  207. package/src/userStats.ts +75 -0
  208. package/src/userStatsConfig.ts +18 -0
  209. package/src/util/computeUnits.js +21 -11
  210. package/src/util/computeUnits.ts +1 -1
  211. package/src/util/getTokenAddress.js +9 -0
  212. package/src/util/getTokenAddress.ts +18 -0
  213. package/src/util/promiseTimeout.js +14 -0
  214. package/src/util/tps.js +27 -0
  215. package/tests/bn/test.ts +46 -11
  216. package/tests/dlob/helpers.ts +620 -0
  217. package/tests/dlob/test.ts +4586 -0
  218. package/yarn-error.log +3160 -0
  219. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
  220. package/lib/admin.d.ts +0 -44
  221. package/lib/admin.js +0 -433
  222. package/lib/clearingHouse.d.ts +0 -133
  223. package/lib/clearingHouse.js +0 -931
  224. package/lib/clearingHouseUser.d.ts +0 -187
  225. package/lib/clearingHouseUser.js +0 -643
  226. package/lib/clearingHouseUserConfig.d.ts +0 -14
  227. package/lib/constants/banks.d.ts +0 -16
  228. package/lib/constants/banks.js +0 -34
  229. package/lib/constants/markets.d.ts +0 -19
  230. package/lib/idl/clearing_house.json +0 -3998
  231. package/lib/math/bankBalance.d.ts +0 -9
  232. package/lib/math/bankBalance.js +0 -75
  233. package/lib/math/state.d.ts +0 -8
  234. package/lib/math/state.js +0 -15
  235. package/lib/orders.d.ts +0 -8
  236. package/lib/orders.js +0 -134
  237. package/src/admin.ts +0 -722
  238. package/src/clearingHouse.ts +0 -1451
  239. package/src/clearingHouseUser.ts +0 -989
  240. package/src/constants/banks.ts +0 -43
  241. package/src/idl/clearing_house.json +0 -3998
  242. package/src/math/bankBalance.ts +0 -112
  243. package/src/math/state.ts +0 -14
  244. package/src/math/utils.js +0 -27
  245. package/src/math/utils.js.map +0 -1
  246. package/src/orders.ts +0 -244
  247. package/src/util/computeUnits.js.map +0 -1
package/lib/types.js CHANGED
@@ -1,23 +1,77 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DefaultOrderParams = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
3
+ exports.DefaultOrderParams = exports.LiquidationType = exports.LPAction = exports.TradeSide = exports.getVariant = exports.isOneOfVariant = exports.isVariant = exports.StakeAction = exports.SettlePnlExplanation = exports.DepositExplanation = exports.SpotFulfillmentStatus = exports.SpotFulfillmentType = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderStatus = exports.MarketType = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.SpotBalanceType = exports.SwapDirection = exports.AssetTier = exports.ContractTier = exports.ContractType = exports.UserStatus = exports.MarketStatus = exports.ExchangeStatus = void 0;
4
4
  const _1 = require(".");
5
5
  // # Utility Types / Enums / Constants
6
+ class ExchangeStatus {
7
+ }
8
+ exports.ExchangeStatus = ExchangeStatus;
9
+ ExchangeStatus.ACTIVE = { active: {} };
10
+ ExchangeStatus.FUNDING_PAUSED = { fundingPaused: {} };
11
+ ExchangeStatus.AMM_PAUSED = { ammPaused: {} };
12
+ ExchangeStatus.FILL_PAUSED = { fillPaused: {} };
13
+ ExchangeStatus.LIQ_PAUSED = { liqPaused: {} };
14
+ ExchangeStatus.WITHDRAW_PAUSED = { withdrawPaused: {} };
15
+ ExchangeStatus.PAUSED = { paused: {} };
16
+ class MarketStatus {
17
+ }
18
+ exports.MarketStatus = MarketStatus;
19
+ MarketStatus.INITIALIZED = { initialized: {} };
20
+ MarketStatus.ACTIVE = { active: {} };
21
+ MarketStatus.FUNDING_PAUSED = { fundingPaused: {} };
22
+ MarketStatus.AMM_PAUSED = { ammPaused: {} };
23
+ MarketStatus.FILL_PAUSED = { fillPaused: {} };
24
+ MarketStatus.WITHDRAW_PAUSED = { withdrawPaused: {} };
25
+ MarketStatus.REDUCE_ONLY = { reduceOnly: {} };
26
+ MarketStatus.SETTLEMENT = { settlement: {} };
27
+ MarketStatus.DELISTED = { delisted: {} };
28
+ class UserStatus {
29
+ }
30
+ exports.UserStatus = UserStatus;
31
+ UserStatus.ACTIVE = { active: {} };
32
+ UserStatus.BEING_LIQUIDATED = { beingLiquidated: {} };
33
+ UserStatus.BANKRUPT = { bankrupt: {} };
34
+ class ContractType {
35
+ }
36
+ exports.ContractType = ContractType;
37
+ ContractType.PERPETUAL = { perpetual: {} };
38
+ ContractType.FUTURE = { future: {} };
39
+ class ContractTier {
40
+ }
41
+ exports.ContractTier = ContractTier;
42
+ ContractTier.A = { a: {} };
43
+ ContractTier.B = { b: {} };
44
+ ContractTier.C = { c: {} };
45
+ ContractTier.SPECULATIVE = { speculative: {} };
46
+ ContractTier.ISOLATED = { isolated: {} };
47
+ class AssetTier {
48
+ }
49
+ exports.AssetTier = AssetTier;
50
+ AssetTier.COLLATERAL = { collateral: {} };
51
+ AssetTier.PROTECTED = { protected: {} };
52
+ AssetTier.CROSS = { cross: {} };
53
+ AssetTier.ISOLATED = { isolated: {} };
54
+ AssetTier.UNLISTED = { unlisted: {} };
6
55
  class SwapDirection {
7
56
  }
8
57
  exports.SwapDirection = SwapDirection;
9
58
  SwapDirection.ADD = { add: {} };
10
59
  SwapDirection.REMOVE = { remove: {} };
11
- class BankBalanceType {
60
+ class SpotBalanceType {
12
61
  }
13
- exports.BankBalanceType = BankBalanceType;
14
- BankBalanceType.DEPOSIT = { deposit: {} };
15
- BankBalanceType.BORROW = { borrow: {} };
62
+ exports.SpotBalanceType = SpotBalanceType;
63
+ SpotBalanceType.DEPOSIT = { deposit: {} };
64
+ SpotBalanceType.BORROW = { borrow: {} };
16
65
  class PositionDirection {
17
66
  }
18
67
  exports.PositionDirection = PositionDirection;
19
68
  PositionDirection.LONG = { long: {} };
20
69
  PositionDirection.SHORT = { short: {} };
70
+ class DepositDirection {
71
+ }
72
+ exports.DepositDirection = DepositDirection;
73
+ DepositDirection.DEPOSIT = { deposit: {} };
74
+ DepositDirection.WITHDRAW = { withdraw: {} };
21
75
  class OracleSource {
22
76
  }
23
77
  exports.OracleSource = OracleSource;
@@ -31,19 +85,16 @@ OrderType.LIMIT = { limit: {} };
31
85
  OrderType.TRIGGER_MARKET = { triggerMarket: {} };
32
86
  OrderType.TRIGGER_LIMIT = { triggerLimit: {} };
33
87
  OrderType.MARKET = { market: {} };
88
+ class MarketType {
89
+ }
90
+ exports.MarketType = MarketType;
91
+ MarketType.SPOT = { spot: {} };
92
+ MarketType.PERP = { perp: {} };
34
93
  class OrderStatus {
35
94
  }
36
95
  exports.OrderStatus = OrderStatus;
37
96
  OrderStatus.INIT = { init: {} };
38
97
  OrderStatus.OPEN = { open: {} };
39
- class OrderDiscountTier {
40
- }
41
- exports.OrderDiscountTier = OrderDiscountTier;
42
- OrderDiscountTier.NONE = { none: {} };
43
- OrderDiscountTier.FIRST = { first: {} };
44
- OrderDiscountTier.SECOND = { second: {} };
45
- OrderDiscountTier.THIRD = { third: {} };
46
- OrderDiscountTier.FOURTH = { fourth: {} };
47
98
  class OrderAction {
48
99
  }
49
100
  exports.OrderAction = OrderAction;
@@ -56,8 +107,8 @@ class OrderActionExplanation {
56
107
  }
57
108
  exports.OrderActionExplanation = OrderActionExplanation;
58
109
  OrderActionExplanation.NONE = { none: {} };
59
- OrderActionExplanation.BREACHED_MARGIN_REQUIREMENT = {
60
- breachedMarginRequirement: {},
110
+ OrderActionExplanation.INSUFFICIENT_FREE_COLLATERAL = {
111
+ insufficientFreeCollateral: {},
61
112
  };
62
113
  OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
63
114
  oraclePriceBreachedLimitPrice: {},
@@ -65,11 +116,63 @@ OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
65
116
  OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
66
117
  marketOrderFilledToLimitPrice: {},
67
118
  };
119
+ OrderActionExplanation.ORDER_EXPIRED = {
120
+ orderExpired: {},
121
+ };
122
+ OrderActionExplanation.LIQUIDATION = {
123
+ liquidation: {},
124
+ };
125
+ OrderActionExplanation.ORDER_FILLED_WITH_AMM = {
126
+ orderFilledWithAMM: {},
127
+ };
128
+ OrderActionExplanation.ORDER_FILLED_WITH_AMM_JIT = {
129
+ orderFilledWithAMMJit: {},
130
+ };
131
+ OrderActionExplanation.ORDER_FILLED_WITH_MATCH = {
132
+ orderFilledWithMatch: {},
133
+ };
134
+ OrderActionExplanation.MARKET_EXPIRED = {
135
+ marketExpired: {},
136
+ };
137
+ OrderActionExplanation.RISK_INCREASING_ORDER = {
138
+ riskingIncreasingOrder: {},
139
+ };
140
+ OrderActionExplanation.ORDER_FILLED_WITH_SERUM = {
141
+ orderFillWithSerum: {},
142
+ };
68
143
  class OrderTriggerCondition {
69
144
  }
70
145
  exports.OrderTriggerCondition = OrderTriggerCondition;
71
146
  OrderTriggerCondition.ABOVE = { above: {} };
72
147
  OrderTriggerCondition.BELOW = { below: {} };
148
+ OrderTriggerCondition.TRIGGERED_ABOVE = { triggeredAbove: {} }; // above condition has been triggered
149
+ OrderTriggerCondition.TRIGGERED_BELOW = { triggeredBelow: {} }; // below condition has been triggered
150
+ class SpotFulfillmentType {
151
+ }
152
+ exports.SpotFulfillmentType = SpotFulfillmentType;
153
+ SpotFulfillmentType.SERUM_v3 = { serumV3: {} };
154
+ class SpotFulfillmentStatus {
155
+ }
156
+ exports.SpotFulfillmentStatus = SpotFulfillmentStatus;
157
+ SpotFulfillmentStatus.ENABLED = { enabled: {} };
158
+ SpotFulfillmentStatus.DISABLED = { disabled: {} };
159
+ class DepositExplanation {
160
+ }
161
+ exports.DepositExplanation = DepositExplanation;
162
+ DepositExplanation.NONE = { none: {} };
163
+ DepositExplanation.TRANSFER = { transfer: {} };
164
+ class SettlePnlExplanation {
165
+ }
166
+ exports.SettlePnlExplanation = SettlePnlExplanation;
167
+ SettlePnlExplanation.NONE = { none: {} };
168
+ SettlePnlExplanation.EXPIRED_POSITION = { expiredPosition: {} };
169
+ class StakeAction {
170
+ }
171
+ exports.StakeAction = StakeAction;
172
+ StakeAction.STAKE = { stake: {} };
173
+ StakeAction.UNSTAKE_REQUEST = { unstakeRequest: {} };
174
+ StakeAction.UNSTAKE_CANCEL_REQUEST = { unstakeCancelRequest: {} };
175
+ StakeAction.UNSTAKE = { unstake: {} };
73
176
  function isVariant(object, type) {
74
177
  return object.hasOwnProperty(type);
75
178
  }
@@ -80,30 +183,56 @@ function isOneOfVariant(object, types) {
80
183
  }, false);
81
184
  }
82
185
  exports.isOneOfVariant = isOneOfVariant;
186
+ function getVariant(object) {
187
+ return Object.keys(object)[0];
188
+ }
189
+ exports.getVariant = getVariant;
83
190
  var TradeSide;
84
191
  (function (TradeSide) {
85
192
  TradeSide[TradeSide["None"] = 0] = "None";
86
193
  TradeSide[TradeSide["Buy"] = 1] = "Buy";
87
194
  TradeSide[TradeSide["Sell"] = 2] = "Sell";
88
195
  })(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
196
+ class LPAction {
197
+ }
198
+ exports.LPAction = LPAction;
199
+ LPAction.ADD_LIQUIDITY = { addLiquidity: {} };
200
+ LPAction.REMOVE_LIQUIDITY = { removeLiquidity: {} };
201
+ LPAction.SETTLE_LIQUIDITY = { settleLiquidity: {} };
202
+ class LiquidationType {
203
+ }
204
+ exports.LiquidationType = LiquidationType;
205
+ LiquidationType.LIQUIDATE_PERP = { liquidatePerp: {} };
206
+ LiquidationType.LIQUIDATE_BORROW = { liquidateBorrow: {} };
207
+ LiquidationType.LIQUIDATE_BORROW_FOR_PERP_PNL = {
208
+ liquidateBorrowForPerpPnl: {},
209
+ };
210
+ LiquidationType.LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
211
+ liquidatePerpPnlForDeposit: {},
212
+ };
213
+ LiquidationType.PERP_BANKRUPTCY = {
214
+ perpBankruptcy: {},
215
+ };
216
+ LiquidationType.BORROW_BANKRUPTCY = {
217
+ borrowBankruptcy: {},
218
+ };
89
219
  exports.DefaultOrderParams = {
90
220
  orderType: OrderType.MARKET,
221
+ marketType: MarketType.PERP,
91
222
  userOrderId: 0,
92
223
  direction: PositionDirection.LONG,
93
224
  baseAssetAmount: _1.ZERO,
94
225
  price: _1.ZERO,
95
- marketIndex: _1.ZERO,
226
+ marketIndex: 0,
96
227
  reduceOnly: false,
97
228
  postOnly: false,
98
229
  immediateOrCancel: false,
99
- triggerPrice: _1.ZERO,
230
+ triggerPrice: null,
100
231
  triggerCondition: OrderTriggerCondition.ABOVE,
101
232
  positionLimit: _1.ZERO,
102
- oraclePriceOffset: _1.ZERO,
103
- padding0: _1.ZERO,
104
- padding1: _1.ZERO,
105
- optionalAccounts: {
106
- discountToken: false,
107
- referrer: false,
108
- },
233
+ oraclePriceOffset: null,
234
+ auctionDuration: null,
235
+ maxTs: null,
236
+ auctionStartPrice: null,
237
+ auctionEndPrice: null,
109
238
  };
package/lib/user.d.ts ADDED
@@ -0,0 +1,228 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="bn.js" />
3
+ import { PublicKey } from '@solana/web3.js';
4
+ import { EventEmitter } from 'events';
5
+ import StrictEventEmitter from 'strict-event-emitter-types';
6
+ import { DriftClient } from './driftClient';
7
+ import { MarginCategory, Order, UserAccount, PerpPosition, SpotPosition } from './types';
8
+ import { UserAccountSubscriber, UserAccountEvents, DataAndSlot } from './accounts/types';
9
+ import { PositionDirection, BN, SpotMarketAccount } from '.';
10
+ import { OraclePriceData } from './oracles/types';
11
+ import { UserConfig } from './userConfig';
12
+ export declare class User {
13
+ driftClient: DriftClient;
14
+ userAccountPublicKey: PublicKey;
15
+ accountSubscriber: UserAccountSubscriber;
16
+ _isSubscribed: boolean;
17
+ eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
18
+ get isSubscribed(): boolean;
19
+ set isSubscribed(val: boolean);
20
+ constructor(config: UserConfig);
21
+ /**
22
+ * Subscribe to User state accounts
23
+ * @returns SusbcriptionSuccess result
24
+ */
25
+ subscribe(): Promise<boolean>;
26
+ /**
27
+ * Forces the accountSubscriber to fetch account updates from rpc
28
+ */
29
+ fetchAccounts(): Promise<void>;
30
+ unsubscribe(): Promise<void>;
31
+ getUserAccount(): UserAccount;
32
+ getUserAccountAndSlot(): DataAndSlot<UserAccount> | undefined;
33
+ /**
34
+ * Gets the user's current position for a given perp market. If the user has no position returns undefined
35
+ * @param marketIndex
36
+ * @returns userPerpPosition
37
+ */
38
+ getPerpPosition(marketIndex: number): PerpPosition | undefined;
39
+ /**
40
+ * Gets the user's current position for a given spot market. If the user has no position returns undefined
41
+ * @param marketIndex
42
+ * @returns userSpotPosition
43
+ */
44
+ getSpotPosition(marketIndex: number): SpotPosition | undefined;
45
+ getEmptyPosition(marketIndex: number): PerpPosition;
46
+ getClonedPosition(position: PerpPosition): PerpPosition;
47
+ /**
48
+ * @param orderId
49
+ * @returns Order
50
+ */
51
+ getOrder(orderId: number): Order | undefined;
52
+ /**
53
+ * @param userOrderId
54
+ * @returns Order
55
+ */
56
+ getOrderByUserOrderId(userOrderId: number): Order | undefined;
57
+ getUserAccountPublicKey(): PublicKey;
58
+ exists(): Promise<boolean>;
59
+ /**
60
+ * calculates the total open bids/asks in a perp market (including lps)
61
+ * @returns : open bids
62
+ * @returns : open asks
63
+ */
64
+ getPerpBidAsks(marketIndex: number): [BN, BN];
65
+ /**
66
+ * calculates the open bids and asks for an lp
67
+ * @returns : lp open bids
68
+ * @returns : lp open asks
69
+ */
70
+ getLPBidAsks(marketIndex: number): [BN, BN];
71
+ /**
72
+ * calculates the market position if the lp position was settled
73
+ * @returns : the settled userPosition
74
+ * @returns : the dust base asset amount (ie, < stepsize)
75
+ * @returns : pnl from settle
76
+ */
77
+ getSettledLPPosition(marketIndex: number): [PerpPosition, BN, BN];
78
+ /**
79
+ * calculates Buying Power = FC * MAX_LEVERAGE
80
+ * @returns : Precision QUOTE_PRECISION
81
+ */
82
+ getBuyingPower(marketIndex: number): BN;
83
+ /**
84
+ * calculates Free Collateral = Total collateral - initial margin requirement
85
+ * @returns : Precision QUOTE_PRECISION
86
+ */
87
+ getFreeCollateral(): BN;
88
+ /**
89
+ * @returns The margin requirement of a certain type (Initial or Maintenance) in USDC. : QUOTE_PRECISION
90
+ */
91
+ getMarginRequirement(marginCategory: MarginCategory, liquidationBuffer?: BN): BN;
92
+ /**
93
+ * @returns The initial margin requirement in USDC. : QUOTE_PRECISION
94
+ */
95
+ getInitialMarginRequirement(): BN;
96
+ /**
97
+ * @returns The maintenance margin requirement in USDC. : QUOTE_PRECISION
98
+ */
99
+ getMaintenanceMarginRequirement(liquidationBuffer?: BN): BN;
100
+ /**
101
+ * calculates unrealized position price pnl
102
+ * @returns : Precision QUOTE_PRECISION
103
+ */
104
+ getUnrealizedPNL(withFunding?: boolean, marketIndex?: number, withWeightMarginCategory?: MarginCategory): BN;
105
+ /**
106
+ * calculates unrealized funding payment pnl
107
+ * @returns : Precision QUOTE_PRECISION
108
+ */
109
+ getUnrealizedFundingPNL(marketIndex?: number): BN;
110
+ getSpotMarketLiabilityValue(marketIndex?: number, marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean): BN;
111
+ getSpotLiabilityValue(tokenAmount: BN, oraclePriceData: OraclePriceData, spotMarketAccount: SpotMarketAccount, marginCategory?: MarginCategory, liquidationBuffer?: BN): BN;
112
+ getSpotMarketAssetValue(marketIndex?: number, marginCategory?: MarginCategory, includeOpenOrders?: boolean): BN;
113
+ getSpotAssetValue(tokenAmount: BN, oraclePriceData: OraclePriceData, spotMarketAccount: SpotMarketAccount, marginCategory?: MarginCategory): BN;
114
+ getNetSpotMarketValue(withWeightMarginCategory?: MarginCategory): BN;
115
+ /**
116
+ * calculates TotalCollateral: collateral + unrealized pnl
117
+ * @returns : Precision QUOTE_PRECISION
118
+ */
119
+ getTotalCollateral(marginCategory?: MarginCategory): BN;
120
+ /**
121
+ * calculates sum of position value across all positions in margin system
122
+ * @returns : Precision QUOTE_PRECISION
123
+ */
124
+ getTotalPerpPositionValue(marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean): BN;
125
+ /**
126
+ * calculates position value in margin system
127
+ * @returns : Precision QUOTE_PRECISION
128
+ */
129
+ getPerpPositionValue(marketIndex: number, oraclePriceData: OraclePriceData): BN;
130
+ getPositionSide(currentPosition: Pick<PerpPosition, 'baseAssetAmount'>): PositionDirection | undefined;
131
+ /**
132
+ * calculates average exit price (optionally for closing up to 100% of position)
133
+ * @returns : Precision PRICE_PRECISION
134
+ */
135
+ getPositionEstimatedExitPriceAndPnl(position: PerpPosition, amountToClose?: BN, useAMMClose?: boolean): [BN, BN];
136
+ /**
137
+ * calculates current user leverage across all positions
138
+ * @returns : Precision TEN_THOUSAND
139
+ */
140
+ getLeverage(): BN;
141
+ getTotalLiabilityValue(): BN;
142
+ getTotalAssetValue(): BN;
143
+ /**
144
+ * calculates max allowable leverage exceeding hitting requirement category
145
+ * @params category {Initial, Maintenance}
146
+ * @returns : Precision TEN_THOUSAND
147
+ */
148
+ getMaxLeverage(marketIndex: number, category?: MarginCategory): BN;
149
+ /**
150
+ * calculates margin ratio: total collateral / |total position value|
151
+ * @returns : Precision TEN_THOUSAND
152
+ */
153
+ getMarginRatio(): BN;
154
+ canBeLiquidated(): boolean;
155
+ isBeingLiquidated(): boolean;
156
+ isBankrupt(): boolean;
157
+ /**
158
+ * Checks if any user position cumulative funding differs from respective market cumulative funding
159
+ * @returns
160
+ */
161
+ needsToSettleFundingPayment(): boolean;
162
+ /**
163
+ * Calculate the liquidation price of a position, with optional parameter to calculate the liquidation price after a trade
164
+ * @param PerpPosition
165
+ * @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
166
+ * @param partial
167
+ * @returns Precision : PRICE_PRECISION
168
+ */
169
+ liquidationPrice(perpPosition: Pick<PerpPosition, 'marketIndex'>, positionBaseSizeChange?: BN): BN;
170
+ /**
171
+ * Calculates the estimated liquidation price for a position after closing a quote amount of the position.
172
+ * @param positionMarketIndex
173
+ * @param closeQuoteAmount
174
+ * @returns : Precision PRICE_PRECISION
175
+ */
176
+ liquidationPriceAfterClose(positionMarketIndex: number, closeQuoteAmount: BN): BN;
177
+ /**
178
+ * Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
179
+ *
180
+ * To Calculate Max Quote Available:
181
+ *
182
+ * Case 1: SameSide
183
+ * => Remaining quote to get to maxLeverage
184
+ *
185
+ * Case 2: NOT SameSide && currentLeverage <= maxLeverage
186
+ * => Current opposite position x2 + remaining to get to maxLeverage
187
+ *
188
+ * Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage
189
+ * => strictly reduce current position size
190
+ *
191
+ * Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage
192
+ * => current position + remaining to get to maxLeverage
193
+ *
194
+ * @param targetMarketIndex
195
+ * @param tradeSide
196
+ * @returns tradeSizeAllowed : Precision QUOTE_PRECISION
197
+ */
198
+ getMaxTradeSizeUSDC(targetMarketIndex: number, tradeSide: PositionDirection): BN;
199
+ /**
200
+ * Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
201
+ * @param targetMarketIndex
202
+ * @param positionMarketIndex
203
+ * @param tradeQuoteAmount
204
+ * @returns leverageRatio : Precision TEN_THOUSAND
205
+ */
206
+ accountLeverageRatioAfterTrade(targetMarketIndex: number, tradeQuoteAmount: BN, tradeSide: PositionDirection, includeOpenOrders?: boolean): BN;
207
+ /**
208
+ * Calculates how much fee will be taken for a given sized trade
209
+ * @param quoteAmount
210
+ * @returns feeForQuote : Precision QUOTE_PRECISION
211
+ */
212
+ calculateFeeForQuoteAmount(quoteAmount: BN): BN;
213
+ /**
214
+ * Calculates a user's max withdrawal amounts for a spot market. If reduceOnly is true,
215
+ * it will return the max withdrawal amount without opening a liability for the user
216
+ * @param marketIndex
217
+ * @returns withdrawalLimit : Precision is the token precision for the chosen SpotMarket
218
+ */
219
+ getWithdrawalLimit(marketIndex: number, reduceOnly?: boolean): BN;
220
+ /**
221
+ * Get the total position value, excluding any position coming from the given target market
222
+ * @param marketToIgnore
223
+ * @returns positionValue : Precision QUOTE_PRECISION
224
+ */
225
+ private getTotalPerpPositionValueExcludingMarket;
226
+ private getOracleDataForPerpMarket;
227
+ private getOracleDataForSpotMarket;
228
+ }